spread in object definition causing undefined properties in "this"

Viewed 70

I have an object which I initialize with bunch of properties in node.js, spreading another object in, and at the end defining a getter.

The problem is the the getter uses this and all the properties defined on the object before the spread don't exist on this.
If I move the spread to the end or start of the object initialization, it works fine.

const obj = { a: 1 }
const obj2 = { 
  prop: 'a',
 ...obj,
 prop2: 'b',
 get test() { 
   return this.prop + this.prop2 
  }
}


console.log(obj2.test); // 'undefinedb'

What can possibly be the reason for that?

Thanks

0 Answers
Related