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
复制代码