gpt4 book ai didi

javascript - 为什么在这种情况下 apply 只需要一个参数?

转载 作者:行者123 更新时间:2023-11-30 09:02:17 25 4
gpt4 key购买 nike

我在学习apply我试图理解为什么我正在研究的代码只传递一个参数来应用。

我首先定义现状:

var Quo = function(string) {
this.status = string;
};

接下来我定义get_status:

Quo.prototype.get_status = function() {
return this.status;
};

我定义了statusObject:

var statusObject = {
status: 'yo!'
};

这就是我迷路的地方:

var status = Quo.prototype.get_status.apply(statusObject);
// status is 'yo!'

根据documentation “应用调用具有给定此值和作为数组提供的参数的函数。”您可以在本例中看到,使用 apply 我只传递了一个参数,我认为它定义了“this”。您能否弄清楚此方法中到底发生了什么,为什么需要应用,以及为什么在这种情况下我只能将一个参数传递给该方法,而它声明需要两个参数。谢谢。

最佳答案

apply 设置应用到第一个参数中提供的对象的函数的上下文。

var o;
function baz(a, b, c) {
//do stuff
}

o = {
foo: 'bar'
};

baz.apply(o);
//this is o
//a is undefined
//b is undefined
//c is undefined

如果将数组作为第二个参数传递,则将根据数组中的值设置参数:

baz.apply(o, [1,2,3]);

//this is o
//a is 1
//b is 2
//c is 3

apply 中的第二个参数是可选的,但是 call 通常用于设置上下文:

//these do the same thing
baz.call(o);
baz.apply(o);

//this is how they're different
baz.call(o, 1, 2, 3);
baz.apply(o, [1, 2, 3]);

关于javascript - 为什么在这种情况下 apply 只需要一个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8300906/

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