DEV Community

Discussion on: JavaScript Basics Before You Learn React

Collapse
 
kjessec profile image
Jesse Chung • Edited

Arrow functions, apart from their aesthetics, have this property called lexical scoping. This explains lexical scoping better than I ever will :)

In short, arrow functions follow the scope of the caller's scope, rather than having its own. function() {} functions' scope can change to whatever by calling .bind() - basically how JS prototype works.

Maybe you deliberately omitted this because in React world arrow functions are mostly used for shorter declaration. But hey, I figured the post might give a wrong impression that arrow function is only for cleaner code :P

Short test code:

class MyClass {
  constructor() {
    this.foo = 'foo';
    this.bar = 'bar';

    // `this` is defined
    this.someFunctionThatTakesACallback(() => {
      console.log(this.foo);
    });

    // In the following function's scope, `this` will be undefined
    // to mitigate this, we need to call .bind (essentially what arrow function does)
    this.someFunctionThatTakesACallback(function() {
      console.log(this.foo);
    });

    // forcing function's scope to be `this`
    this.someFunctionThatTakesACallback(function() {
      console.log(this.foo);
    }.bind(this));
  }

  someFunctionThatTakesACallback(callback) {
    callback();
  }
}

new MyClass();

Enter fullscreen mode Exit fullscreen mode


`

Collapse
 
nathansebhastian profile image
Nathan Sebhastian

Ah yes, sorry if I skip the part about this. Thanks for adding it here, Jesse :)