Equivalent to BookController in ES6 using the class.
No, this is not equivalent, it is noticeably different. Your class example is essentially equivalent to this ES5:
function BookController { this.books = []; } BookController.prototype.getBook = function getBook(index) { return this.books[index]; };
Note that getBook defined in the prototype that will be assigned to instances when using the new BookController . But this is not what your first example does. In the first example, for each instance, another getBook assigned as a "private" (non-inheritable) property.
In the getBook function, I want to make sure that the context is always a BookController , so I want to add this alias to BookController in ES6.
This is not an alias, this is a link. You do this the same way (in the constructor), but without the need for a variable:
// EcmaScript 6 class BookController { constructor() { this.books = []; this.getBook = index => { return this.books[index]; }; } }
Since the arrow function closes above this .
Example:
Note, however, that for no specific reason to do this, the normal thing is to leave this caller.
source share