问题描述
例如,我知道可以在Javascript中将键值设置为先前的键值
I know its possible to set a key value with a preceding key value in Javascript for example
var obj = {
one: "yes",
two: obj.one
}
obj [two]现在等于是"
obj[two] is now equal to "yes"
当按键在功能中时,如何设置值
How do i go about setting the value when the keys are in a function
var obj = {
one: function () {
return(
two: "yes"
three: ?? //I want to set three to the value of two
)
}
}
我想让三个包含两个值,即obj.one()应该返回{两个:是",三个:是"}
I want to have three contain the value of two i.e obj.one() should return {two: "yes", three: "yes"}
推荐答案
您的第一个代码也不起作用.它抛出TypeError: obj is undefined
.
Your first code doesn't work neither. It throws TypeError: obj is undefined
.
您可以使用
var obj = new function(){
this.one = "yes",
this.two = this.one
}; // { one: "yes", two: "yes" }
对于第二个,您可以使用
For the second one, you can use
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
都会产生该对象的新副本.如果要重用上一个,
Note each call of one
will produce a new copy of the object. If you want to reuse the previous 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对象中为键值分配另一个键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!