2

Why the following code will output 1 ?

function func(){
  alert(this)
}
var i = 1;
func.call(i);
J.c
  • 23
  • 3
  • 1
    `MDN` is your friend: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call – Adam Jenkins Jun 02 '15 at 17:07

2 Answers2

2

Definition

function.prototype.call(this,arg1,arg2,...);

Thus, when you call func.call, the first argument you pass in is bound to this variable. So in the function func, any this variable will be replaced with your first argument which is 1.

To play further

You can extend more arguments to func and call with further arguments and see what happen:

function func(a,b){
    alert(this + a*b);
}

func.call(1,2,3);

Recall the definition, the first argument or func.call refers to this variable of func. So you'll end up running

alert( 1 + 2*3 );

** Ref: ** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

** Even further reading **

function.prototype.call has another close sibling which is function.prototype.apply. The first argument of both functions refers to this variable. The only difference is function.prototype.apply accepts arguments of such function in array.

So instead of

func.call(1,2,3);

You will call it by

func.apply(1,[2,3]);

Have fun playing with it!

TaoPR
  • 5,932
  • 3
  • 25
  • 35
1

Because the first argument of call is the functions this value, the syntax is

function.call(thisArg[, arg1[, arg2[, ...]]])

as noted on MDN

Meaning whatever is passed as the first argument to call will be this inside the called function

function func(){
  alert(this)
}

func.call("test"); // alerts "test"

To pass arguments, you pass a this value, and then the rest of the arguments would be the arguments passed along to the function

function func(arg1, arg2, arg3){
    alert(this); // alerts "this_value"
    alert(arg2); // alerts "kitty"
}

func.call("this_value", "hello", "kitty", "cat");

apply works the same way, but takes an array of arguments instead

func.apply("this_value", ["hello", "kitty", "cat"]);
Oka
  • 23,367
  • 6
  • 42
  • 53
adeneo
  • 312,895
  • 29
  • 395
  • 388