gpt4 book ai didi

javascript - 将键值分配给 JavaScript 对象中的另一个键值

转载 作者:行者123 更新时间:2023-11-27 23:42:16 26 4
gpt4 key购买 nike

我知道可以在 Javascript 中设置一个带有前面键值的键值

var obj = {
one: "yes",
two: obj.one
}

obj[two] 现在等于“yes”

当按键位于函数中时,如何设置值

var obj = {
one: function () {
return(
two: "yes"
three: ?? //I want to set three to the value of two
)
}
}

我想让三个包含二的值,即 obj.one() 应该返回 {two: "yes", Three: "yes"}

最佳答案

您的第一个代码也不起作用。它抛出TypeError:obj未定义

你可以使用

var obj = new function(){
this.one = "yes",
this.two = this.one
}; // { one: "yes", two: "yes" }

对于第二个,您可以使用

var obj = {
one: function () {
return new function() {
this.two = "yes",
this.three = this.two
};
}
};
obj.one(); // { two: "yes", three: "yes" }
obj.one() === obj.one(); // false

请注意,每次调用 one 都会生成该对象的一个​​新副本。如果您想重复使用前一个,

var obj = {
one: (function () {
var obj = new function() {
this.two = "yes",
this.three = this.two
};
return function(){ return obj }
})()
};
obj.one(); // { two: "yes", three: "yes" }
obj.one() === obj.one(); // true

关于javascript - 将键值分配给 JavaScript 对象中的另一个键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33574082/

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