Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
JavaScript, 5 ways to call a function
This post is part of a series called JavaScript Demystified.

Time after time I find JavaScript code that has bugs caused by lack of proper understanding of how functions work in JavaScript (a lot of that code has been written by me, by the way.) JavaScript has functional programming characteristics, and that can get in our way until we decide to face and learn it.

For starters, let's examine five ways to invoke a function. On the surface we might be tempted to think that functions work exactly like C#, but we will see that there are important differences and ignoring them will undoubtedly result in hard to track bugs.

Let's first create a simple function that we will be using through the rest of this post. This function will just return an array with the current value of this and the two supplied arguments.

<script type="text/javascript">
function makeArray(arg1, arg2){
	return [ this, arg1, arg2 ];
}
</script>

Most common way, unfortunately, global function calls

When we are learning JavaScript we learn how to define functions using the syntax used in the example above. We learn that it's also very easy to call that function — all we need to do is:

makeArray('one', 'two');
// => [ window, 'one', 'two' ]

Wait a minute. What's that window object doing there? Why is it the value of this? If you haven't stopped to think about it, please stay with me here.

In JavaScript, and I'm not talking specifically about the browser here, there's a default/global object. It's as if every code that we write which seems to be just "loose" inside your script (i.e. outside of any object declaration) is actually being written in the context of that global object. In our case, that makeArray function isn't just a loose "global" function, it's a method of the global object. Bringing ourselves back to the browser, the global object is mapped to the window object in this environment. Let's prove that.

alert( typeof window.methodThatDoesntExist );
// => undefined
alert( typeof window.makeArray);
// => function

What all this means is that calling makeArray like we did before is the same as calling as follows.

window.makeArray('one', 'two');
// => [ window, 'one', 'two' ]

I say it's unfortunate that this is the most common way because it leads us to declare our functions globally by default. And we all know that global members are not exactly the best practice in software programming. This is especially true in JavaScript. Avoid globals in JavaScript, you won't regret it.

JavaScript function invocation rule #1 In a function called directly without an explicit owner object, like myFunction(), causes the value of this to be the default object (window in the browser).

Method call

Let's now create a small object and use the makeArray function as one of its methods. We will declare the object using the literal notation. Let's also call this method.

//creating the object
var arrayMaker = {
	someProperty: 'some value here',
	make: makeArray
};

//invoke the make() method
arrayMaker.make('one', 'two');
// => [ arrayMaker, 'one', 'two' ]
// alternative syntax, using square brackets
arrayMaker['make']('one', 'two');
// => [ arrayMaker, 'one', 'two' ]

See the difference here? The value of this became the object itself. You may be wondering why isn't it still window since that's how the original function had been defined. Well, that's just the way functions are passed around in JavaScript. Function is a standard data type in JavaScript, an object indeed; you can pass them around and copy them. It's as if the entire function with argument list and body was copied and assigned to make in arrayMaker. It's just like defining arrayMaker like this:

var arrayMaker = {
	someProperty: 'some value here',
	make: function (arg1, arg2) {
		return [ this, arg1, arg2 ];
	}
};
JavaScript function invocation rule #2 In a function called using the method invocation syntax, like obj.myFunction() or obj['myFunction'](), causes the value of this to be obj.

This is a major source of bugs in event handling code. Look at these examples.

<input type="button" value="Button 1" id="btn1"  />
<input type="button" value="Button 2" id="btn2"  />
<input type="button" value="Button 3" id="btn3"  onclick="buttonClicked();"/>

<script type="text/javascript">
function buttonClicked(){
	var text = (this === window) ? 'window' : this.id;
	alert( text );
}
var button1 = document.getElementById('btn1');
var button2 = document.getElementById('btn2');

button1.onclick = buttonClicked;
button2.onclick = function(){   buttonClicked();   };
</script>

Clicking the first button will display "btn1" because it's a method invocation and this will be assigned the owner object (the button input element.) Clicking the second button will display "window" because buttonClicked is being called directly (i.e. not like obj.buttonClicked().) This is the same thing that happens when we assign the event handler directly in the element's tag, as we have done for the third button. Clicking the third button does the same of the second button.

That's another advantage of using a library like jQuery. When defining event handlers in jQuery, the library will take care of overriding the value of this and make sure it contains a reference to the element that was the source of the event.

//using jQuery
$('#btn1').click( function() {
	alert( this.id ); // jQuery ensures 'this' will be the button
});

How does jQuery override the value of this? Keep reading.

Two more: apply() and call()

The more you leverage functions in JavaScript, the more you find yourself passing functions around and needing to invoke them in different contexts. Just like jQuery does in the event handler functions, you'll often need to override the value of this. Remember I told you functions are objects in JavaScript? Functions have predefined methods, two of them are apply() and call(). We can use them to do precisely that kind of overriding.

var gasGuzzler = { year: 2008, model: 'Dodge Bailout' };
makeArray.apply( gasGuzzler, [ 'one', 'two' ] );
// => [ gasGuzzler, 'one' , 'two' ]
makeArray.call( gasGuzzler,  'one', 'two' );
// => [ gasGuzzler, 'one' , 'two' ]

The two methods are similar. The first parameter will override this. They differ on the subsequent arguments. Function.apply() takes an array of values that will be passed as arguments to the function and Function.call() takes the same arguments separately. In practice I believe you'll find that apply() is more convenient in most cases.

JavaScript function invocation rule #3 If we want to override the value of this without copying the function to another object, we can use myFunction.apply( obj ) or myFunction.call( obj ).

Constructors

I won't delve into the details of defining types in JavaScript but at minimum we should be aware that there aren't classes in JavaScript and that any custom type needs a constructor function. It's also a good idea to define the methods of your type using the prototype object, which is a property of the constructor function. Let's create a small type.

//declaring the constructor
function ArrayMaker(arg1, arg2) {
	this.someProperty = 'whatever';
	this.theArray = [ this, arg1, arg2 ];
}
// declaring instance methods
ArrayMaker.prototype = {
	someMethod: function () {
		alert( 'someMethod called');
	},
	getArray: function () {
		return this.theArray;
	}
};

var am = new ArrayMaker( 'one', 'two' );
var other = new ArrayMaker( 'first', 'second' );

am.getArray();
// => [ am, 'one' , 'two' ]

What's very important to note here is the presence of the new operator before the function call. Without that your function will just be called like a global function and those properties that we are creating would be created on the global object (window.) And you don't want to do that. Another issue is that, because you typically don't have an explicit return value in your constructor function, you'll end up assigning undefined to some variable if you forget to use new. For these reasons it's a good convention to name your constructor functions starting with an upper case character. This should serve as a reminder to put the new operator before the call.

With that taken care of, the code inside the constructor is very similar to any constructor you probably have written in other languages. The value of this will be the new object that you are trying to initialize.

JavaScript function invocation rule #4 When used as a constructor, like new MyFunction(), the value of this will be a brand new object provided by the JavaScript runtime. If we don't explictly return anything from that function, this will be considered its return value.

It's a wrap

I hope understanding the differences between the invocation styles help you keeping bugs out of your JavaScript code. Some of these bugs can be very tricky do identify and making sure you always know what the value of this will be is a good start to avoiding them in the first place.


Posted 02-09-2009 12:03 AM by sergiopereira

[Advertisement]

Comments

DotNetShoutout wrote JavaScript, 5 ways to call a function - Sergio Pereira
on 02-09-2009 6:05 AM

Thank you for submitting this cool story - Trackback from DotNetShoutout

Elijah Manor wrote re: JavaScript, 5 ways to call a function
on 02-09-2009 7:00 AM

Wow.. that is some great stuff!

Keep up the great work!

http://twitter.com/elijahmanor

http://zi.ma/webdev

http://zi.ma/techtwitterings

Dew Drop - February 9, 2009 | Alvin Ashcraft's Morning Dew wrote Dew Drop - February 9, 2009 | Alvin Ashcraft's Morning Dew
on 02-09-2009 9:20 AM

Pingback from  Dew Drop - February 9, 2009 | Alvin Ashcraft's Morning Dew

DotNetKicks.com wrote JavaScript, 5 wyas to call a function
on 02-09-2009 9:56 AM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Dustin Sparks wrote re: JavaScript, 5 ways to call a function
on 02-09-2009 1:37 PM

This is a pretty good, and useful, explanation of all the ways to call functions. Rule number 4 is particularly useful as it explains a lot about packages out there and the way they program things. I also never thought about the context at which functions where being stored as global. So that is some knowledge that will most definitely become useful. - bookmarked

Arjan`s World » LINKBLOG for February 9, 2009 wrote Arjan`s World &raquo; LINKBLOG for February 9, 2009
on 02-09-2009 1:55 PM

Pingback from  Arjan`s World    &raquo; LINKBLOG for February 9, 2009

rascunho » Blog Archive » links for 2009-02-09 wrote rascunho &raquo; Blog Archive &raquo; links for 2009-02-09
on 02-09-2009 3:09 PM

Pingback from  rascunho  &raquo; Blog Archive   &raquo; links for 2009-02-09

Bruno Campagnolo de Paula weblog » Resumo do dia para 2009-02-09 wrote Bruno Campagnolo de Paula weblog &raquo; Resumo do dia para 2009-02-09
on 02-09-2009 9:25 PM

Pingback from  Bruno Campagnolo de Paula weblog &raquo; Resumo do dia para 2009-02-09

Reflective Perspective - Chris Alcock » The Morning Brew #283 wrote Reflective Perspective - Chris Alcock &raquo; The Morning Brew #283
on 02-10-2009 3:31 AM

Pingback from  Reflective Perspective - Chris Alcock  &raquo; The Morning Brew #283

Jags wrote re: JavaScript, 5 ways to call a function
on 02-10-2009 3:59 AM

Learned so much from this article..its a keeper..and its going to my google bookmarks!!

Thanks a lot for sharing this :)

My Bad Attitude » JavaScript, 5 ways to call a function wrote My Bad Attitude &raquo; JavaScript, 5 ways to call a function
on 02-11-2009 3:41 PM

Pingback from  My Bad Attitude &raquo; JavaScript, 5 ways to call a function

K. Adam Christensen wrote re: JavaScript, 5 ways to call a function
on 02-11-2009 4:48 PM

One thing I think it's worth pointing out is that you can still write named functions and not have it be contained in the window scope.

Enter closures.

<pre name="code" class="js:nogutter">

(function () {

   function make(arg1, arg2) {

       return [this, arg1, arg2];

   }

   alert(typeof make);

   // function

   alert(typeof this.make);

   // undefined

   alert(typeof window.make);

   // undefined

})();

alert(typeof make);

// undefined

alert(typeof this.make);

// undefined

alert(typeof window.make);

// undefined

</pre>

Due to the scoping nature, things change up a bit

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 02-12-2009 12:28 AM

@K, great point. You kind of stole my thunder from a future post that I had planned :)

Daniel Teng wrote Weekly links #1
on 02-15-2009 5:00 AM

关于敏捷

FixingtheAgileEngineeringProblemblog.gdinwiddie.com/.../fixing-the-agile-en...

Sergio Pereira wrote JavaScript, time to grok closures
on 02-23-2009 8:37 AM

This post is part of a series called JavaScript Demystified . When I wrote about functions in JavaScript

Community Blogs wrote JavaScript, time to grok closures
on 02-23-2009 9:10 AM

This post is part of a series called JavaScript Demystified . When I wrote about functions in JavaScript

JavaScript?????????????????? - ?????????????????? - ??????IT???????????????????????? wrote JavaScript?????????????????? - ?????????????????? - ??????IT????????????????????????
on 03-01-2009 8:54 PM

Pingback from  JavaScript?????????????????? - ?????????????????? - ??????IT????????????????????????

Justin wrote re: JavaScript, 5 ways to call a function
on 04-05-2009 8:22 AM

Thanks Sergio - this post is getting printed on real paper and laminated YEAH!!

jQuery Howto wrote re: JavaScript, 5 ways to call a function
on 04-30-2009 2:04 AM

Thanks for the article. Crystal clear :)

Ashish Jain wrote re: JavaScript, 5 ways to call a function
on 05-19-2009 6:57 AM

Amazing article... Very clear...

Samrat wrote re: JavaScript, 5 ways to call a function
on 07-22-2009 9:10 AM

wow.. good stuff.. made a lot of things clear.

与时俱进 wrote JavaScript,5种调用函数的方法
on 09-17-2009 4:59 AM

这篇文章详细的介绍了Javascript中各种函数调用的方法及其原理,对于理解JavaScript的函数有很大的帮助!一次又一次的,我发现,那些有bug的Javascript代码是由于没有真正理解Ja...

Jarnis wrote re: JavaScript, 5 ways to call a function
on 10-30-2009 7:18 AM

Thanks for the explanation. I'm not sure it made javascript less strange in my mind, but I guess understanding the quirks and peculiarities of the language is a big part of mastering it. I have a feeling this may help a lot in understanding why some scriprs are structured as they are. Very helpfull :)

Sergio Pereira wrote Guided Tour: jQuery - Array wannabes
on 12-23-2009 11:16 AM

This post is part of a series called the Guided Tours . In this second installment we are still looking

Sergio Pereira wrote Guided Tour: jQuery - Array wannabes
on 12-23-2009 11:17 AM

This post is part of a series called the Guided Tours . In this second installment we are still looking

Xpost wrote re: JavaScript, 5 ways to call a function
on 01-06-2010 12:14 PM

Nice info, very helpful. This go to my favorites. Thanks for sharing

esv wrote re: JavaScript, 5 ways to call a function
on 03-09-2010 1:20 AM

First change your back ground color which is in black....

ben.mcintyre wrote re: JavaScript, 5 ways to call a function
on 03-21-2010 9:18 PM

GREAT article.  This explains things more clearly than any I've seen so far.

One question.  In the final example, I'm assuming that the way someProperty and someMethod are declared are equivalent.  In other words, if someProperty was declared in the bottom section on the prototype, this would be exactly the same, as would the case where someMethod was declared in the initial function/object declaration.

Is this the case ?

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 03-21-2010 10:32 PM

@ben

It's not exactly the same. Anything you declare in the object's prototype will be shared by all instances of that object type, that's why it makes more sense to use it for methods and constants, for example.

If you had someProperty in the prototype, the value used in the last constructed object would override the value in all the other existing instances.

hadi wrote re: JavaScript, 5 ways to call a function
on 03-24-2010 7:28 PM

The built-in Date object has the following behavior:

- if called with new, it will return an object

x = new Date();

typeof(x); //object

- if called without new, it will return a string.

x = Date();

typeof(x); //string

Does anyone knows how is it implemented?

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 03-24-2010 10:08 PM

@hadi

function Date2(y, m, d) {
	this.year = y;
	this.month = m;
	this.day = d;
	return y + '-' + m + '-' + d; // <=== this creates the string
}

var d1 = new Date2(2010, 11, 30);
alert(typeof d1); // --> object
var d2 = Date2(2010, 11, 30);
alert(typeof d2); // --> string
duMah wrote re: JavaScript, 5 ways to call a function
on 05-24-2010 5:22 PM

thx a lot!

i readed "JS - good parts" by D.Crockford and stucked at that part.

i spent few hours on my pc to make myself  understand it, and your article helped me greatly.

PS: is there a Function.prototype and how i can use it (and what for use it).

thx again

sry for my english, i'm from Poland:P

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 05-24-2010 7:59 PM

@duMah, there is a Function.prototype object, that's where apply() and call() come from.

You can use it to, for example, add methods that operate on any function. If you take a look in the Prototype.js library you will see that it adds a few methods in there, like curry() and bindAsEventListener().

duMah wrote re: JavaScript, 5 ways to call a function
on 05-25-2010 2:17 PM

i made such experiment:

var f = function (){ return hello; },

   o = { say: function (){ return this.hello } };

document.writeln(f.hello); //undefined

document.writeln(f()); //error-unknown variable

document.writeln(o.hello); //undefined

document.writeln(o.say()); //undefined

Object.prototype.hello = "i'm object";

document.writeln(f.hello); //"i'm object"

document.writeln(f()); //"i'm object"

document.writeln(o.hello); //"i'm object"

document.writeln(o.say()); //"i'm object"

Function.prototype.hello = "i'm function";

document.writeln(f.hello); //"i'm function"

document.writeln(f()); //"i'm object"

document.writeln(o.hello); //"i'm object"

document.writeln(o.say()); //"i'm object"

document.writeln(f.apply(o,[])); //"i'm object"

document.writeln(o.say.apply(f,[])); //"i'm function"

and one thing suprised me:

Function.prototype.hello = "i'm function";

document.writeln(f.hello); //"i'm function"

document.writeln(f()); //"i'm object" <<this i don't understand

why it has value of object and not of function?

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 05-25-2010 3:27 PM

@duMah, looks like you never changed f. The f function is still the same as when you started, a single "return hello;" statement.

Maybe you meant to update the Object's prototype instead of the Function's prototype near the end of your example?

duMah wrote re: JavaScript, 5 ways to call a function
on 05-25-2010 3:59 PM

that's not, what i meant

i was wondering why " f.hello " gives value from Function.prototype, and " f() ", which do " return hello ", gives value from Object.prototype?

as for me, it should return same value - those from Function.prototype

in other words, basing on next example:

Object.prototype.hello = "Obj Proto hello";

Function.prototype.hello = "Func Proto hello";

function f(){ return hello; }

document.writeln(f.hello); //"Func Proto hello" <<ok for me

document.writeln(f()); //"Obj Proto hello"  << why not "Func Proto hello"?

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 05-25-2010 6:53 PM

@duMah, why would it return something from the Function prototype when it's got nothing to do with it?

"hello" is a global variable, which is the same as a property of the window object, which is NOT a function, so it return Object.prototype.hello.

duMah wrote re: JavaScript, 5 ways to call a function
on 05-26-2010 5:57 PM

ok, i get it

global variables are properties of global object, in browser case - window:

document.writeln(window.hello); //undefined

document.writeln(hello); //undefined

var hello = "glob var hello";

document.writeln(window.hello); //"glob var hello"

document.writeln(hello); //"glob var hello"

Object.prototype.hello = "obj proto hello";

document.writeln(window.hello); //"glob var hello"

document.writeln(hello); //"glob var hello"

delete hello;

document.writeln(window.hello); //"glob var hello"

document.writeln(hello); //"glob var hello"

last 3 lines suprised me, why i can't delete variable hello?

sorry for asking so many questions, but i like to know, how things, which i'm going to use, works :P

i feel ashamed to not be able to understand it by myself

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 05-26-2010 8:23 PM

@duMah, "hello" is not precisely a global var and not a direct property of window, it comes through the inheritance chain. If you try "delete Object.prototype.hello" I think it will do what you want.

Mohammed AbdelRahman wrote re: JavaScript, 5 ways to call a function
on 07-26-2010 7:09 AM
Walter Becl wrote re: JavaScript, 5 ways to call a function
on 07-29-2010 7:47 PM

This is still a great article and explanation.  It will stand the test of time.

lonely wrote re: JavaScript, 5 ways to call a function
on 08-24-2010 9:00 PM

confusing.  You said in the title javascript 5 way to call function. All I see is badly explain array, jquery, prototype basic use. And I see 10 snippets instead 5.

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 08-24-2010 9:39 PM

@lonely, I'm sorry. The text assumes the reader already knows a little bit of JS. I was not trying to explain arrays or prototype, that's presumed knowledge for this article.

Sorry about the 10 snippets too, I'll try to get better next time.

You constructive comment is welcome.

Mike Grace wrote re: JavaScript, 5 ways to call a function
on 09-04-2010 9:56 PM

This was great! I found your post after reading through some published JS code and wanted to know what the .call function was. Your article was well written and really helped improve my understanding of JS functions. Thank you!

Simon wrote re: JavaScript, 5 ways to call a function
on 09-28-2010 4:42 AM

Thanks Sergio for a very clear and structured explanation.

Well done, and thanks for sharing :)

David wrote re: JavaScript, 5 ways to call a function
on 11-13-2010 1:07 AM

Thanks for explanation.

Jeff Rafter wrote re: JavaScript, 5 ways to call a function
on 11-28-2010 11:23 AM

Thanks for this article. I seriously re-read it once per month. Never ever take your blog down please! Cheers.

Software Developement wrote re: JavaScript, 5 ways to call a function
on 02-10-2011 1:05 AM

I was trying to find about global functions in javascript and your article help me a lot thanks .. 5 Stars..

Dawesi wrote re: JavaScript, 5 ways to call a function
on 02-19-2011 8:30 PM

Nice work. Just brushing up on my js... Libraries like jQuery and ExtJs are awesome... .call() and .apply() are soooo useful, epecially to change the scope in which they are run.

Thanks for this article, it's a great resource.

ElanHasson.com wrote JavaScript, 5 ways to call a function - Sergio Pereira - Devlicio.us - Just the Tasty Bits
on 02-28-2011 10:49 AM

JavaScript, 5 ways to call a function - Sergio Pereira - Devlicio.us - Just the Tasty Bits Source: devlicio.us Agile .NET ALT.NET very helpful.

Javier Moreno wrote re: JavaScript, 5 ways to call a function
on 03-20-2011 3:35 PM

This is the best explanation of the context scope I've read so far :-) Thanks a lot!

jv

Quora wrote What are some ways to call a Javascript function?
on 03-27-2011 6:52 PM

Sergio Pereira, JavaScript, 5 ways to call a function: devlicio.us/.../javascript-5-ways-to-call-a-function.aspx

Kozie wrote re: JavaScript, 5 ways to call a function
on 04-18-2011 3:56 AM

Thanks for sharing this article ;)

Finally understand call() now. Besides that, i now also know about apply().

Thanks again! Keep up the good work ;)

KJ wrote re: JavaScript, 5 ways to call a function
on 05-12-2011 6:24 PM

Thank you, this post save my hell a lot of time! Although I've spent a lot of time already..

Javad wrote re: JavaScript, 5 ways to call a function
on 06-19-2011 6:24 AM

Thank you for this awesome article.

you just opened to me a new view about javascript.

God bless you.

Hristo wrote re: JavaScript, 5 ways to call a function
on 08-03-2011 4:10 PM

Hello and thanks for the great summery of JS functions.

I've met the following functions issue, which I can't understand:

function loadem(){

im = imFold + imPrefix + numPad(++imNum) + imSuffix;

(function(im){

var pIm = new Image();

pIm.onerror = function(){

                                        // doing stuff

}

pIm.onload = function(){

       // doing stuff

setTimeout(loadem, 0);

}

pIm.src = im;

})(im);

}

Why or what is the function definition or maybe a call in "...(function(im){...})(im);".

Cheers

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 08-03-2011 7:23 PM

@Hristo, that's a common question. What that construct means is that we are creating a function and immediately calling it, sometimes passing a parameter ("im" in your case).

Some people call these "Immediate Functions".

This format is useful especially for initialization code, where you may have a lot of code that will run only at that time and never again. Putting all that code inside an immediate function means it will be thrown away after the function executes (since there's no way to run that code again anyway), freeing up some memory.

To break it down for you: after the first "(" you create an anonymous function with the code you want to run immediately. That function may or may not receive parameters. After the function's closing "}" you close the parenthesis you had opened at the beginning. So what you have at this point is a function expression wrapped in parenthesis. The last bit is the pair of parenthesis to invoke that function, containing any parameters to be passed to the anonymous function.

The reason you need to wrap the anonymous function with parenthesis is that you'd get syntax errors if you didn't.

As a small fun fact, you can have that formatted in two slightly different ways:

1 - (function(){ /* code */ })();

2 - (function(){ /* code */ }());

I hope this helped you.

tasos wrote re: JavaScript, 5 ways to call a function
on 08-24-2011 9:18 AM

Hello and thanks for this great article.

I need some help.I can't understand "

JavaScript function invocation rule #3 If we want to override the value of this without copying the function to another object, we can use myFunction.apply( obj ) or myFunction.call( obj ).

".

I don't understand it.You say "without copying".

So is it copied otherwise?

Btw this way we can't pass any arguments.right?

Thank you in advance!

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 08-24-2011 12:18 PM

@tasos

I was just trying to say you can do this:

obj2.method1.apply( obj1, [param1, param2] );

Instead of:

obj1.method1 = obj2.method1; //copying

obj1.method1(param1, param2);

And regarding the parameters, you can see how I passed parameters to apply above.

tasos wrote re: JavaScript, 5 ways to call a function
on 08-24-2011 3:10 PM

Thank you again :)

PSobczak bLoG wrote Articles
on 09-09-2011 10:56 AM

Articles

satya wrote re: JavaScript, 5 ways to call a function
on 09-22-2011 7:19 AM

Great work and nicely presented.

But I had a problem with firefox. Only firefox(8-aurora now) is behaving differently in my case.

My case:

I have a class on my main document with some prototype methods. I am copying these prototypes to each iframe loaded. While accessing the method from iframe(without reference) I am getting "this"(inside function) as window. But in all other browsers(including <<FF8) it is giving iframeWindow.

The same issue came in firefox sometimes back. We logged a defect and they solved it. But now they reverted the solution by saying it as expected behavior. The reverted solution will be available in FF8.

Bug ID:  bugzilla.mozilla.org/show_bug.cgi

In the above there is sample code attached to reproduce the issue.

As they mentioned, using obj.methodName() is not possible for me.

Here I have couple of questions:

1. Is it correct what ever they mentioned in the bug?

2. Is there any other way to get the iframeWindow in my case?

Please help to get out this problem.

Thanks in advance

--Satya

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 09-22-2011 9:13 AM

@Satya

I'd suggest that you try to get those answers from them using whatever they offer, like mailing list or message boards. Unfortunately I cannot help you with this issue.

satya wrote re: JavaScript, 5 ways to call a function
on 09-23-2011 1:10 AM

Thanks....

Grillermo wrote re: JavaScript, 5 ways to call a function
on 10-16-2011 10:21 PM

I couldnt understand many things here, you make too many assumptions about what the reader knows, it seems that this is for people who already know what you are saying, you are just remind them. Maybe thats the point and i'm wrong for expecing it to be newbie friendly.

vimal wrote re: JavaScript, 5 ways to call a function
on 10-18-2011 6:43 AM

Very good article! It clarified things I was looking for.

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 10-18-2011 9:30 AM

@Grillermo not sure what you're talking about. Could you be more specific about which assumptions you didn't follow?

Of course there are assumptions, right? This is definitely not an introductory level article. If you need some extra help I can point you to better material.

sachin kumar wrote re: JavaScript, 5 ways to call a function
on 11-11-2011 5:59 AM

Really nice artilce. I have been using 2-3 ways of Calling function in javascript and never tried to compare all methods of Javascript. Nice aritcle! . Please keep posting such nice aritlces

SoftConnection wrote re: JavaScript, 5 ways to call a function
on 12-09-2011 2:24 AM

really nice, thanks for clarifying this for us. *thumbs up*

as wrote re: JavaScript, 5 ways to call a function
on 12-13-2011 3:56 AM

这篇文章详细的介绍了Javascript中各种函数调用的方法及其原理,对于理解JavaScript的函数有很大的帮助!一次又一次的,我发现,那些有bug的Javascript代码是由于没有真正理解

rameye wrote re: JavaScript, 5 ways to call a function
on 03-17-2012 11:31 PM

Thank you very much. I no longer am mystified as to why the use of foo.call() or foo.apply() when viewing javascript

library method implementations.  Also helped me squash a nasty "xxx.parentNode is undefined" error in a script. I shouldn't run into that again now that I understand these inner workings of a javascript function. Great article!

human person wrote re: JavaScript, 5 ways to call a function
on 04-13-2012 9:16 PM

Good stuff...

Boojie wrote re: JavaScript, 5 ways to call a function
on 05-15-2012 2:07 PM

Nice job. Thx.

Christoph wrote re: JavaScript, 5 ways to call a function
on 05-29-2012 3:48 AM

Thank you for this good article. Helped me a lot!

CODE WEB Tips wrote JavaScript, 5 ways to call a function - Sergio Pereira - Devlicio.us - Just the Tasty Bits
on 06-02-2012 12:46 AM

Time after time I find JavaScript code that has bugs caused by lack of proper understanding of how functions work in JavaScript (a lot of that code has been written by me, by the way.) JavaScript has ...

bengm wrote re: JavaScript, 5 ways to call a function
on 06-12-2012 12:02 PM

Thanks! just what I was looking for. No matter how many times I read up on it, I always forget what 'this' is in each context.

Cedik wrote re: JavaScript, 5 ways to call a function
on 08-13-2012 6:08 AM

Thanks for the post, it was useful (the part with apply() and call() in particular, I didn't know those methods existed).

However, I was looking for some info on the

name = (function() {

something;

})();

structure. I saw it on some github projects and I can't figure out why is it used like that.

Marek wrote re: JavaScript, 5 ways to call a function
on 08-15-2012 12:23 PM

Good work! I was trying to keep up and did a bit more research and published blog.i-evaluation.com/.../javascript-call-and-apply . There are few more example there so it might be nice extension to what have been said here.

Kishore wrote re: JavaScript, 5 ways to call a function
on 09-25-2012 1:14 AM

Perfect Explanation!

I'm searching for call & apply methods functionality.. found this master piece..

JavaScript Training wrote re: JavaScript, 5 ways to call a function
on 10-13-2012 7:36 AM

Fantastic Tutorial. Very informative on hidden concept.

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 01-12-2013 6:38 PM

@Cedik, the construct you are asking about is commonly called "self-invoking anonymous function". It's basically a cuntion declaration that gets called right after it's declared (the parenthesis at the end are calling the function). The function need to be wrapped in parenthesis because some browsers don't like if do simply:  function(){ /* something */ }();

cent wrote re: JavaScript, 5 ways to call a function
on 01-22-2013 6:18 AM

...something I almost forgotted: all javascript libraries nowadays use self-invoking anonymous functions which I find way beyond the programming standards of other languages.

I simply prefer the construction of an empty object and everything added upon it afterwards:

//construct a global Function object

function MYLIB(){}

//a built-in type as property

MYLIB.property1="abc"

//an object as property

MYLIB.property2=new Prop2_constructor();

//function

MYLIB.a_function1 = function(arg1, arg2){

//...some code

}

...

wecode wrote re: JavaScript, 5 ways to call a function
on 02-02-2013 1:56 AM

Beautiful... I found what i was looking for. Had a issue with function call it was working with the event but not with the javascript call sorted out

Thanks

Web design by mehedi wrote re: JavaScript, 5 ways to call a function
on 05-11-2013 2:48 PM

This is an awesome explanation. This helped me a lot to understand how to teach a student.

Web design tutor HASSAN wrote re: JavaScript, 5 ways to call a function
on 05-11-2013 2:52 PM

This is an awesome tutorial. This tutorial helped me to understand how to teach my students.

Alexey Poklonskiy wrote re: JavaScript, 5 ways to call a function
on 05-13-2013 2:23 PM

Is this really what you wanted to do?

// declaring instance methods  

ArrayMaker.prototype = {  

   someMethod: function () {  

       alert( 'someMethod called');  

   },  

   getArray: function () {  

       return this.theArray;  

   }  

};  

In this way you've overridden the  ArrayMaker.prototype that was created by JS when you created ArrayMaker function. The (possibly) unwanted effect of it is that Array.Maker.prototype has lost the constructor property that was pointing at the ArrayMaker function.

Wouldn't the code below be better to preserve the OO style?

ArrayMaker.prototype.someMethod = function () {  

       alert( 'someMethod called');  

}

ArrayMaker.prototype.getArray = function () {  

       return this.theArray;  

}  

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 05-13-2013 4:30 PM

@Alexey, I did override the entire prototype but in this case the prototype was empty and I had no use for the constructor property. I was only trying to explain how constructors behave.

But you're right, the way you suggested is recommended over what I showed.

Thanks.

Nerd wrote re: JavaScript, 5 ways to call a function
on 06-20-2013 7:43 AM

Thanks, i prefer the jquery method

find man wrote re: JavaScript, 5 ways to call a function
on 06-25-2013 6:29 AM

Thanks for the good script and able to understand java script in a better way

aznrjz@gmail.com wrote re: JavaScript, 5 ways to call a function
on 08-22-2013 1:06 AM

I do not even know how I ended up here, but I thought this post was great. I don't know who you are but definitely you are going to a famous blogger if you are not already ;) Cheers!

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 08-22-2013 4:05 PM

@aznjr, thanks. One day, when I grow up, I want to be a celebrity blogger and bathe in all the glamour. Well, maybe not :) Kind words like yours are more than I could ask for.

ericky wrote re: JavaScript, 5 ways to call a function
on 08-26-2013 5:40 AM

It's amazing!

It's made me  understanding javascript  deeply.

thanks very much

by the way

i like your verification style.

Gabriele Guizzardi wrote re: JavaScript, 5 ways to call a function
on 10-15-2013 9:06 PM
Leo wrote re: JavaScript, 5 ways to call a function
on 10-16-2013 8:12 AM

very insightful info. I will share this information to my javascript friends circle.

sergiopereira wrote re: JavaScript, 5 ways to call a function
on 10-18-2013 9:26 AM

@Gabriele, thanks. I've already talked to the blog owner and he added the proper link to this original post.

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)