Sergio Pereira

Sponsors

The Lounge

Wicked Cool Jobs

Syndication

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....

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
<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)

CodeBetter.Com