Can someone please explain why defining a prototype function with lambda expression doesn\'t work? I thought this must be asked before but couldn\'t find it.
One of the chief features of arrow functions is that they close over the this from the context in which they're created; they don't get it based on how they're called like other functions do. So...
// ...whatever `this` is *here*
Book.prototype.printTitle2 = () => {
// ...is what `this` will be *here*
console.log(this.title);
};
But your function relies on this varying depending on how it's called.
This just isn't a use-case for arrow functions. Use a normal 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);
}
}