What’s the meaning of this?!express
The other benefit of using arrow functions with promises/callbacks is that it reduces the confusion surrounding the this keyword. In code with multiple nested functions, it can be difficult to keep track of and remember to bind the correct this context. In ES5, you can use workarounds like the .bind method (which is slow) or creating a closure using var self = this;.promise
Because arrow functions allow you to retain the scope of the caller inside the function, you don’t need to create self = this closures or use bind.bash
Developer Jack Franklin provides an excellent practical example of using the arrow function lexical this to simplify a promise:ide
Without Arrow functions, the promise code needs to be written something like this:ui
// ES5this
API.prototype.get = function(resource) {
var self = this;
return new Promise(function(resolve, reject) {
http.get(self.uri + resource, function(data) {
resolve(data);
});
});
};
Using an arrow function, the same result can be achieved more concisely and clearly:
// ES6
API.prototype.get = function(resource) {
return new Promise((resolve, reject) => {
http.get(this.uri + resource, function(data) {
resolve(data);
});
});
};
複製代碼
You can use function expressions if you need a dynamic this and arrow functions for a lexical this.spa
另一個小技巧是:爲了區別究竟是代碼塊仍是一個object,須要用()來包含返回值。prototype
//ES5
var setNameIdsEs5 = function setNameIds(id, name) {
return { id: id, name: name };
};
// ES6
var setNameIdsEs6 = (id, name) => ({ id: id, name: name });
//若是沒有()則不知道是代碼塊仍是object
複製代碼