使用JavaScript对象中的另一个键值分配键值

时间:2015-11-06 19:17:26

标签: javascript javascript-objects

我知道可以在Javascript中使用前面的键值设置键值,例如

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

obj [two]现在等于"是"

如何在键处于功能

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

我希望有三个包含两个值,即obj.one()应该返回{two:" yes",三个:" yes"}

2 个答案:

答案 0 :(得分:1)

您的第一个代码也不起作用。它抛出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

答案 1 :(得分:0)

试试这个

var obj = {
    one: function () {
            this.two = "yes"
            this.three = "??"
    }
}

console.log(obj)
console.log(obj.one())
console.log(obj)