1

From what I learned arrow functions don't have a this keyword,it takes the parents this value. So how does this work? Doesn't the value for this in the func property point to the window object? How does it point to the class and return the name?

class app {
constructor(name){
this.name=name
}

func() => {return this.name}
}

let a = new app('william')
a.func()
// william

1 Answers1

1

The code you posted initializes func as an instance variable, not a class method. Thus it's as if your class declaration looked like:

class app {
  constructor(name) {
    this.func = () => {return this.name};
    this.name=name;
  }
}

The name = value syntax in a class declaration is not universally supported yet (as far as I know).

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Even if it is defined like that I fail to see how the this keyword refers to the name and not the window object? –  Jun 16 '19 at 19:36
  • @CevapMaster because it is exactly as if the code looked like what I posted. Inside the constructor, `this` refers to the newly-created object because the constructor function is not an `=>` function. – Pointy Jun 16 '19 at 19:37
  • @CevapMaster you can read more [here](https://www.sitepoint.com/javascript-private-class-fields/). – Pointy Jun 16 '19 at 19:39
  • Okay I understand the function will be set to the newly created object. But the arrow functions this refers to the constructors environment doesn't it ? So how does it work? –  Jun 16 '19 at 19:43
  • No, again the new not-yet-standard "field" syntax is quite surprising in how it works. Look at the code I posted. Inside the `constructor()` function, any reference to `this` — inside or outside a `=>` function — is going to refer to the new object being initialized. – Pointy Jun 16 '19 at 19:44
  • The "field" declaration stuff is not standard yet. As far as I can tell my fairly recent version of Node doesn't accept it (without some weird Node flag). – Pointy Jun 16 '19 at 19:45
  • First time I am seeing this to be honest. Interesting. I thought arrow functions always get their this value from the environment. –  Jun 16 '19 at 19:47
  • @CevapMaster they do; that's what makes the "field" syntax so weird. The apparent location of the `=>` function is not where it's actually handled; it's literally as if the parser relocates all the field declarations into the `constructor()` function as `this.foo` initializations. – Pointy Jun 16 '19 at 19:50
  • So what you're trying to tell me is that every this inside the constructor function always points to the newly created object no matter what? –  Jun 16 '19 at 20:29
  • @CevapMaster yes, except inside nested "old-style" `function` blocks. Like you said, `=>` functions use the contextual `this`, and the contextual `this` *inside* the constructor function is the newly-created object. – Pointy Jun 16 '19 at 20:33