Skip to content

Instantly share code, notes, and snippets.

@brauliodiez
Last active June 20, 2017 10:06
Show Gist options
  • Save brauliodiez/7979d3150940e28d0dd4b07de3c7908c to your computer and use it in GitHub Desktop.
Save brauliodiez/7979d3150940e28d0dd4b07de3c7908c to your computer and use it in GitHub Desktop.
ES6 Fat arrow, solving the 'this' problem

Arrow functions

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

steps

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment