admin管理员组

文章数量:1316012

Edit: this question was asked due to my misunderstanding. Proceed with caution, as reading it might waste your time.

I thought call and apply would execute a function given a set of arguments, but I'm getting confusing test results. See my test code:

window.z = 0;
(function(){++(window.z)}).call(this, 1, 2, 3)

I would expect z to be 3 after execution. However, z is 1.

(function(){++(window.z)}).apply(this, [1, 2, 3])

Same here. z == 1;
I tried simply logging the input argument as well:

var x = function(y){console.log(y);}
x.call(this, 1, 2, 3);

Result? Only 1 is logged.
What am I doing wrong here?

(Tested in Chrome and Firefox with Firebug.)

Edit: this question was asked due to my misunderstanding. Proceed with caution, as reading it might waste your time.

I thought call and apply would execute a function given a set of arguments, but I'm getting confusing test results. See my test code:

window.z = 0;
(function(){++(window.z)}).call(this, 1, 2, 3)

I would expect z to be 3 after execution. However, z is 1.

(function(){++(window.z)}).apply(this, [1, 2, 3])

Same here. z == 1;
I tried simply logging the input argument as well:

var x = function(y){console.log(y);}
x.call(this, 1, 2, 3);

Result? Only 1 is logged.
What am I doing wrong here?

(Tested in Chrome and Firefox with Firebug.)

Share Improve this question edited Dec 22, 2011 at 15:24 Protector one asked Dec 22, 2011 at 15:09 Protector oneProtector one 7,3315 gold badges67 silver badges88 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Both call and apply only call the function once. The difference is how the arguments to the invocation are passed.

With call, each parameter after the context (first parameter), is a parameter. With apply, the second parameter should be an array like object of parameters (the first parameter still provides the context).

function foo(a, b, c) {

};

foo.call(this, 1, 2, 3); // a == 1, b == 2, c == 3;
foo.apply(this, [1,2,3]); // a == 1, b == 2, c == 3;

If you want to call the function multiple times, you can acplish this by simply putting the call in a loop.

It seems that you are under the impression that the call and apply methods should call the functon once for each parameter. That is not the case, it only calls the function once.

The apply methods takes an array of arguments:

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

The call methods takes an argument list:

func.call(this, 1, 2, 3);

This is expected, the arguments you pass will be present in your increment function (as arguments see here for reference), but you are only calling the function once.

本文标签: Javascript call and apply functions only called on first argumentStack Overflow