gpt4 book ai didi

javascript - NodeJS 对象内的匿名函数

转载 作者:行者123 更新时间:2023-12-03 07:46:09 24 4
gpt4 key购买 nike

为什么以下代码不返回“a 和 b”?

Staff.config = {
a: 'a constant',
b: (function(){
return this.a + ' and b';
})()
};

console.log(Staff.config) // { a: 'a constant', b: 'undefined and b' }

最佳答案

(function(){ return this.a + ' and b'; })() is getting executed under the global scope(this refers to window in browser) and in your case, global context does not have property a hence it is undefined.

更简单的解决方案是使用函数表达式作为b的值,因此Staff.config.b()将返回预期的输出。

var Staff = {};
Staff.config = {
a: 'a constant',
b: function() {
return this.a + ' and b';
}
};
alert(Staff.config.b());

You could achieve the same using getter which gets the value of a specific property

试试这个:

var Staff = {};
Staff.config = {
a: 'a constant',
get b() {
return this.a + ' and b';
}
};
alert(Staff.config.b);

关于javascript - NodeJS 对象内的匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35195847/

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