使用 JavaScript 对象中的另一个键值分配键值
Assign Key Value with another key value in JavaScript Object
我知道可以使用 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() 应该 return {二:"yes",三:"yes"}
试试这个
var obj = {
one: function () {
this.two = "yes"
this.three = "??"
}
}
console.log(obj)
console.log(obj.one())
console.log(obj)
您的第一个代码也不起作用。它抛出 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
我知道可以使用 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() 应该 return {二:"yes",三:"yes"}
试试这个
var obj = {
one: function () {
this.two = "yes"
this.three = "??"
}
}
console.log(obj)
console.log(obj.one())
console.log(obj)
您的第一个代码也不起作用。它抛出 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