Assign Key Value with another key value in JavaScript Object [closed]

老子叫甜甜 提交于 2019-12-11 11:54:16

问题


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] 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
                  )
             }
          }

I want to have three contain the value of two i.e obj.one() should return {two: "yes", three: "yes"}


回答1:


Your first code doesn't work neither. It throws TypeError: obj is undefined.

You can use

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

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



回答2:


Try this

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

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


来源:https://stackoverflow.com/questions/33574082/assign-key-value-with-another-key-value-in-javascript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!