例如,我知道可以在 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
)
}
}
我想让 3 包含 2 的值,即 obj.one() 应该返回 {two: "yes", Three: "yes"}
你的第一个代码也不起作用。它抛出TypeError: obj is undefined
.
您可以使用
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)