0

how to object value to its on property object ?

I tried like this

var obj = {
 a:2,
 b:this.a   
}

Then try obj.b it is giving undefined ..can I make function in object?

Expected output 2

user5711656
  • 3,310
  • 4
  • 33
  • 70
  • 1
    You can't do that. Also, obvious duplicate is obvious. –  Apr 25 '18 at 10:19
  • how to achieve this in different approach ? – user5711656 Apr 25 '18 at 10:20
  • 4
    Possible duplicate of [Self-references in object literal declarations](https://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – Nope Apr 25 '18 at 10:21

1 Answers1

1
const obj = {
  a: 2,
  get b() {
    return this.a;
  }
};

console.log(obj.b);

const obj2 = {
  a: 2,
  b: function() {
    return this.a;
  }
};

console.log(obj2.b());

See it in action: https://jsfiddle.net/rqnbxw86/

Mario Murrent
  • 712
  • 5
  • 24
anttud
  • 736
  • 3
  • 9