繁体   English   中英

在javascript中传递参数

[英]Passing Arguments in 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
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.methodthis将是指1但作为this总是必须引用的对象 (在非严格的环境), 1被转换成Number对象。

最后一个值是undefined因为您实际上仅将23 (两个参数)传递给方法(而不是三个)。

因此,最后,代码将执行以下操作:

var obj = new Number(1);
obj.method = Foo.prototype.method;
obj.method(2,3);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM