Assign Key Value with another key value in JavaScr

2019-08-10 19:50发布

问题:

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)