gpt4 book ai didi

javascript - 如何访问不同对象的函数

转载 作者:行者123 更新时间:2023-11-30 12:39:31 24 4
gpt4 key购买 nike

我有以下代码-

function test() {
a = {
name : 'John',
greeting : 'Hello',
sayIt : function() {
return this.greeting + ', ' +
this.name + '!';
}
};

b = {
name : 'Jane',
greeting : 'Hi'
};
}

如何使用 b 访问 sayIt?当然b.say是不行的。我需要打印“嗨,简”。如何将 b 的名称和问候语传递给 sayIt 函数?

最佳答案

您可以使用applycall

a.sayIt.apply(b);

这些改变了 this 的值。

关于javascript - 如何访问不同对象的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24956918/

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