How to alias in JavaScript 2015 (EcmaScript 6)?

In EcmaScript 5, we can alias this as var ctrl = this , as shown in the following snippet.

 // EcmaScript 5 function BookController { var ctrl = this; ctrl.books = []; ctrl.getBook = getBook; function getBook(index) { return ctrl.books[index]; } } 

BookController equivalent in ES6 using class . I had a scenario in which getBook is called with this , other than BookController . 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.

 // EcmaScript 6 class BookController { constructor() { this.books = []; } getBook(index) { return this.books[index]; } } 

How is the this alias in JavaScript 2015 (EcmaScript 6)?

+5
source share
1 answer

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:

 // EcmaScript 6 class BookController { constructor() { this.books = []; this.getBook = index => { return this.books[index]; }; } } let c1 = new BookController(); c1.books.push("The Hitchhiker Guide to the Galaxy"); let f1 = c1.getBook; let c2 = new BookController(); c2.books.push("Do Androids Dream of Electric Sheep?"); let f2 = c2.getBook; console.log(f1(0)); console.log(f2(0)); 

Note, however, that for no specific reason to do this, the normal thing is to leave this caller.

+7
source

All Articles