在javascript中传递参数

时间:2011-09-19 16:42:06

标签: javascript

我想了解以下行为,因为对此网站javascript garden的解释对我来说还不够。

如果你能给我一个明确的解释,我将不胜感激 内联评论中的问题。

这里的例子是:

function Foo() {}

Foo.prototype.method = function(a, b, c) {
    console.log(this, a, b, c);
};

Foo.method = function() {
    Function.call.apply(Foo.prototype.method, arguments);
};


Foo.prototype.method(1,2,3) // Foo { method=function()} 1 2 3 //this output is obvious
Foo.method(1,2,3)  // Number {} 2 3 undefined // I want understand why the first argument is a number and the last one is undefined

1 个答案:

答案 0 :(得分:7)

Function.call.apply(Foo.prototype.method, arguments);

相同
Foo.prototype.method.call(arguments[0], arguments[1], arguments[2], ...);

,在您的情况下,与:

相同
Foo.prototype.method.call(1, 2, 3);

这意味着,在Foo.prototype.method内,this会引用1but as this always has to reference an object(在非严格环境中),1会转换为{ {1}}对象。

最后一个值为Number,因为您实际上只将undefined2(两个参数)传递给方法(而不是三个)。

所以最后,代码正在做类似的事情:

3