Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"}

like image 915
lboyel Avatar asked Dec 02 '25 09:12

lboyel


1 Answers

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
like image 96
Oriol Avatar answered Dec 05 '25 00:12

Oriol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!