2

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

1

3 Answers 3

8

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)

Sign up to request clarification or add additional context in comments.

Comments

5

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"

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.