What’s the meaning of this?!
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;.
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.
Developer Jack Franklin provides an excellent practical example of using the arrow function lexical this to simplify a promise:
Without Arrow functions, the promise code needs to be written something like this:
// ES5
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.
另外一个小技巧是:为了区别到底是代码块还是一个object,需要用()来包含返回值。
//ES5
var setNameIdsEs5 = function setNameIds(id, name) {
return { id: id, name: name };
};
// ES6
var setNameIdsEs6 = (id, name) => ({ id: id, name: name });
//如果没有()则不知道是代码块还是object