gpt4 book ai didi

javascript - 在 JavaScript 中传递参数

转载 作者:行者123 更新时间:2023-12-02 17:29:04 24 4
gpt4 key购买 nike

我想了解以下行为,因为此网站上的解释 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.method 中,this 将引用 1, but as this always has to reference an object (在非严格环境中),1 被转换为 Number 对象。

最后一个值是未定义,因为您实际上只将23(两个参数)传递给方法(而不是三个) .

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

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

关于javascript - 在 JavaScript 中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7474348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com