Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrow function in class

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!!

like image 629
Đức Hoàng Avatar asked Mar 24 '26 15:03

Đức Hoàng


1 Answers

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.

like image 83
CertainPerformance Avatar answered Mar 27 '26 05:03

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!