this - Javascript call method -
why following code output 1 ?
function func(){    alert(this)  }  var = 1;  func.call(i);
definition
function.prototype.call(this,arg1,arg2,...);
thus, when call func.call, first argument pass in bound this variable. in function func, this variable replaced first argument 1.
to play further
you can extend more arguments func , call further arguments , see happen:
function func(a,b){     alert(this + a*b); }  func.call(1,2,3); recall definition, first argument or func.call refers this variable of func. you'll end running 
alert( 1 + 2*3 ); ** ref: ** https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/function/call
** further reading **
function.prototype.call has close sibling function.prototype.apply. first argument of both functions refers this variable. difference function.prototype.apply accepts arguments of such function in array.
so instead of
func.call(1,2,3); you call by
func.apply(1,[2,3]); have fun playing it!
Comments
Post a Comment