0

I have a Function constructor A

function A(){
   this.number = 10;
   this.show = () => console.log(this.number)
}

So, I'm creating an object with this constructor

let a = new A();
//a={
//   number: 10, 
//   show: () => console.log(this.number)
//}

And plain object b

let b = {
   number: 20,
   show: () => console.log(this.number)
}

As result, I can say objects a and b syntactically equal a == b, but why

a.show() // gives 10
b.show() // undefined

I understand that for b, 'this' is a global object, that is why it is undefined in this case, but why there is different behavior for a?

  • Class bodies create a new execution context, object literals don’t. This and everything else you need to know about `this` is explained in the linked posts. – Sebastian Simon Oct 15 '21 at 04:11
  • @SebastianSimon: Do you mean function bodies? Because there are no classes here and class bodies also don't create an execution context. – Felix Kling Oct 15 '21 at 07:23

0 Answers0