I have a question on '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 internally?
does humanWithHand variable copies (or points?) its properties and members to human variable's prototype?
Yehuda Katz has a good writeup of JavaScript's
Function#call
method. His writeup should answer your question, and many followup questions besides.When you call a function directly, using the general syntax:
Then
this
inside the function call is whateverthis
is outside the function call. By default, in the browser,this
outside any function calls iswindow
. So inside the function call as above,this
is also by defaultwindow
.When you call a function using the method-call syntax:
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 set up a function outside an object and want to call it with
this
inside the function call set to an object, you can:You can use this technique to pass arguments as well:
.call()
sets thethis
value and then calls the function with the arguments you passed to.call()
. You use.call()
instead of just calling the function directly when you want to set thethis
value inside the called function rather than let it be set to whatever javascript would normally set it to..apply()
is a sister function. It can also set thethis
value and it can take arguments in an array so it can be used when you are trying to pass a variable argument list from some other function call or when you're constructing an argument list programmatically which may have different numbers of arguments depending upon the situation.