How to "call" work in javascript?

I have a question about the "call" in javascript.

var humanWithHand = function(){ this.raiseHand = function(){ alert("raise hand"); } } var humanWithFoot = function(){ this.raiseFoot = function(){ alert("raise foot"); } } var human = function(){ humanWithHand.call( this ); humanWithFoot.call( this ); } var test = new human(); 

so..when I use 'call' as humanWithHand.call (this), what happens inside?

Does humanWithHand contain variables (or points?) its properties and members for the prototype of a human variable?

+8
javascript call
source share
2 answers

.call() sets this , and then calls the function with the arguments passed to .call() . You are using .call() , and not just calling the function directly when you want to set the this value inside the called function, rather than letting it install any JavaScript code that usually installs it.

.apply() is a sister function. It can also set this , and it can take arguments in an array, so it can be used when you try to pass a list of variable arguments from some other function call or when you arbitrarily create an argument list that can have a different number of arguments depending from the situation.

+7
source share

Yehuda Katz has a good JavaScript Function#call method entry . His entry should answer your question and many subsequent questions.

When you call a function directly using the general syntax:

 var foo = function() { console.log("foo"); return this; }; foo(); // evaluates to `window` 

Then this inside the function call is that this is outside the function call. By default, this browser has a window outside of any function calls. Thus, inside the function call, as indicated above, this also the default window .

When you call a function using the call method syntax:

 var bar = { foo: function() { console.log("foo"); return this; } }; bar.foo(); // evaluates to `bar` 

Then this inside the function call is the object to the left of the rightmost period: in this case, bar .

We can simulate this situation using call .

When you configure a function outside the object and want to call it using this inside the function call set for the object, you can:

 var foo = function() { console.log("foo"); return this; } var bar = { }; foo.call(bar); // evaluates to `bar` 

You can also use this technique to pass arguments:

 var foo = function(arg1, arg2) { console.log("foo"); return arg1 + arg2; } var bar = { }; foo.call(bar, "abc", "xyz"); // evaluates to `"abcxyz"` 
+9
source share

All Articles