例如,我知道在Javascript中用前面的键值设置键值是可能的。
var obj = {
one: "yes",
two: obj.one
}Obj-2现在等于“是”。
当键在函数中时,如何设置值?
var obj = {
one: function () {
return(
two: "yes"
three: ?? //I want to set three to the value of two
)
}
}我希望有三个包含两个的值,即obj.one()应该返回{2:“是”,三:“是”}
发布于 2015-11-06 19:42:51
你的第一段代码也不起作用。它抛出了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发布于 2015-11-06 19:30:20
尝尝这个
var obj = {
one: function () {
this.two = "yes"
this.three = "??"
}
}
console.log(obj)
console.log(obj.one())
console.log(obj)https://stackoverflow.com/questions/33574082
复制相似问题