tags:

views:

249

answers:

3

Hopefully the title is self explanatory, what is the advantage of using the .call() method in Javascript compared with just writing functionName(); ?

+5  A: 

If you don't pass anything into call(), it will be the same; the function will be run with the same scope that the call to call() is made:

function test() {
    alert(this);
}

test(); // alerts the window object
test.call(); // alerts the window object

But if you pass an object into call(), that object will be used as the scope:

test.call("hi"); // alerts "hi"
Ates Goral
+8  A: 

functionName.call() takes an object instance as its first parameter. It then runs functionName within the context of that object instance (ie "this" is the specified instance)

David Arno
Thanks, that makes sense.
jonhobbs
+1  A: 

Let me show an example:

<html>
<head>
<script type="text/javascript">
 var developerName = "window";
function test(){
   var developer = function(developerName ){ this.developerName  = developerName;}
    developer.prototype = {
      displayName : function(){alert(this.developerName );}
    }
    var developerA = new developer("developerA");
    var developerB = new developer("developerB");
    developerA.displayName();//will display an alert box with "developerA" as its inner text
    developerA.displayName.call();//will display an alert box with "window" as its inner text, in this case the context is the window object.
    developerA.displayName.call(developerB);//will display an alert box with "developerB" as its inner text
}
</script>
</head>
<body>
<input type="button" onclick="test()" value="display names"/>
<body>
</html>

Further reading:
http://www.alistapart.com/articles/getoutbindingsituations

Hope this helps.

Jaime Febres