1
const myO = {
  myf: () => {
    console.log(this);
  },
};

myO.myf();   // this === window

In object literal, this refers to window;

class MyObject {
  myf = () => {
    console.log(this);
  };
}
const myObject = new MyObject();
myObject.myf();   //  this === MyObject  

In an object instantiated from a class, this refers to the object.

Why is the difference?

Question is marked as duplicated but I really can't see any resemblance

  • “What this means in simpler terms is that the arrow function *retains the `this` value from its context* and does not have its own this..” — that’s the relevant bit from the accepted answer in the duplicate. When assigned in the class, `this` is different in the scope. – user2864740 Oct 17 '20 at 18:23
  • I’ve voted to re-open because this comes down to the context of `this` in a specific (class syntax) context, which might be overlooked / not expected. – user2864740 Oct 17 '20 at 18:25
  • I understand that an arrow function dose not bind "this" to anything and the scope of "this" is inherited from its lexical environment. So I want to know why in the 2nd case "this" is bound to the object. Does it has something to do with the instantiation process? – Toffee Conmigo Oct 17 '20 at 18:42
  • Well, the value of `this` should answer that question.. when the object literal is created the scope of `window` (global). However, *inside the class keyword/definition..* – user2864740 Oct 17 '20 at 18:50
  • Then the *actual question, which would not be a duplicate of the current close target,* might be “What is the scope of assigning to a property inside a class definition?” (Which is entirely separate from the first construct, and only an extension of the behavior of the “understood” arrow function binding, which *is a duplicate* of the linked question.) – user2864740 Oct 17 '20 at 18:53
  • That's indeed what I want to ask. Thanks. – Toffee Conmigo Oct 17 '20 at 19:18

0 Answers0