An arrow function has a shorter syntax that a function expression and does not bind its own this. arguments, super or new.target.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Let's emulate an async call after a given timeout, if we do it in the traditional way, when the timeout is resolved, the this element inside that call will point to window.
class ClientAPI {
constructor(discount) {
this.discount = discount;
}
getClientData() {
const promise = new Promise(
function (resolve) {
setTimeout(function() {
resolve({id: 23, product: 'Shoes', amount: 200 * (this.discount / 100)});
}, 500)
}
);
return promise;
}
}
const clientAPI = new ClientAPI(10);
clientAPI.getClientData().then(
(data) => {
console.log(data);
}
);
Now we can see that _amount_field contains NaN
Notedown we would fix this by just adding a bind.this or self approach.
In ES6 we can use the fat arrow workaround:
class ClientAPI {
constructor(discount) {
this.discount = discount;
}
getClientData() {
const promise = new Promise(
- function (resolve) {
+ (resolve) => {
- setTimeout(function() {
+ setTimeout(() => {
resolve({id: 23, product: 'Shoes', amount: 200 * (this.discount / 100)});
}, 500)
}
);
return promise;
}
}
const clientAPI = new ClientAPI(10);
clientAPI.getClientData().then(
(data) => {
console.log(data);
}
);
Now this is pointing to the ClientAPI instance.