3

Code 1:

class X1 {
  x = 1;
  get = () => this;
}
a = new X1();
console.log(a.get());

Code 2:

var X1={
    x:1,
    get:()=>this
}
console.log(X1.get())

I don't know why result of code 1 is X1 but code 2 is Window. Hope guys can help me!!

1 Answer 1

5

Class fields are syntax sugar for assigning in the constructor. Code 1 is equivalent to:

class X1 {
  constructor() {
    this.x = 1;
    this.get = () => this;
  }
}

Inside the constructor, this refers to the instance being created - the a. Arrow functions inherit this from their outer scope. So this.get = () => this; results in the returned this being the same as the this in the outer scope - the instance, or the a.

In Code 2, the outer scope is the top level. this on the top level is either the global object (in a browser, that's window), or undefined. So, the arrow function get which returns this returns the this on the top level - in sloppy mode in a browser, that's the window.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.