0
class dog extends animal {
    speakAge = (age) => console.log(this.calcAge('dog', age));
}

i do not understand how does it work? this not a method like

class dog extends animal {
    speakAge(age) { console.log(this.calcAge('dog', age)) } ;
}

what are those called? and do they have lexical scope ?

Nish
  • 353
  • 3
  • 9

1 Answers1

1

They are called Arrow functions, introduced in ES6. Arrow functions were created to simplify function scope and make using the ‘this’ keyword much more straightforward. While in ES5 ‘this’ referred to the parent of the function, in ES6, arrow functions use lexical scoping — ‘this’ refers to its current surrounding scope and no further. Thus the inner function knew to bind to the inner function only, and not to the object’s method or the object itself.

Edit: As pointed out in comments, Arrow functions aren’t methods, they’re anonymous function expressions, so the only way to add them to a class is by assignment to a property.

For example,

class Dog {
  constructor(name, bread) {
    this.name = name;
    this.bread = bread;
    // functions
    this.bark = () => {
      return `Bark Bark! My name is ${this.name}`;
    }
  }
}
const mini = new Dog('Leo', 'Pug');
mini.bark();
Bhavesh Lohana
  • 376
  • 3
  • 5