1

When I create the prototype out of scope, but referencing it I can not reach the nome property.

'use strict';

function Cachorro(nome) {
    this.nome = nome;

    this.late = () => {
        console.log(`${this.nome}: Au au au!`);
    }
};

Cachorro.prototype.morde = () => {
    console.log(`${this.nome}: #mordendo`);
}

const dolly = new Cachorro("Dolly");


dolly.late()
dolly.morde()
  • 1
    That's the point of using an arrow function. Don't use an arrow function. – Quentin Jul 12 '16 at 13:53
  • Related: [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/q/34361379/218196) – Felix Kling Jul 12 '16 at 20:47

1 Answers1

2

The reason is that ES6 arrow functions always inherit this of the parent scope. Because of this, you do not want to use them for prototype functions since this would be the only way to get at that object instance's properties.

So convert this:

Cachorro.prototype.morde = () => {
    console.log(`${this.nome}: #mordendo`);
}

to:

Cachorro.prototype.morde = function() {
    console.log(`${this.nome}: #mordendo`);
}
mscdex
  • 93,083
  • 13
  • 170
  • 135