Let obj = {a: 1, b: 2*this.a} this does not get a, is it a this problem or can only call a function?

ask for the big answer:
let obj = {a: 1, b: 2*this.a} so you can"t get a, is it a this problem or can you only call a function?

Apr.09,2021

at this time, this does not point to obj, and you cannot get an in obj, because the object has not yet been generated and has not been assigned to obj, so obj is still undefined


.
let obj = {a: 1, b: 2*this.a} 

obj.b // 2 * window.a

it is not realistic that you want to use the properties in the object, because when calculating this property, it is impossible for your object to be created yet.

it looks like this:

 let obj = {a: 1, b: 2 * obj.a} 


so to achieve such a function, you need:

 let obj = {a: 1, b: () => 2 * obj.a}
  
  obj.b()

or this is fine, but

is not recommended.
obj = {a: 1, b: function() {return 2 * this.a}}
  
  :
  
  obj.b()

let obj={a:1};
obj.b=2*obj.a;

the reference to this refers to other responses, so I won't talk nonsense.
if you want to use the value of a for this question, you can use it like this

.
function Obj() {
    this.a = 1;
    this.b = 2 * this.a;
}
var obj = new Obj();
console.log(obj.b);
Menu