One of the main features of arrow functions is that they close above this from the context in which they are created; they do not get it based on what they are called, like other functions. So that...
// ...whatever `this` is *here* Book.prototype.printTitle2 = () => { // ...is what `this` will be *here* console.log(this.title); };
But your function depends on this , changing depending on what it's called.
It is simply not used for arrow functions. Use the regular function:
Book.prototype.printTitle2 = function() { console.log(this.title); };
Or better yet, use the new class syntax:
class Book { constructor(title, year) { this.title = title; this.year = year; } printTitle2() { console.log(this.title); } }
Tj crowder
source share