Announcement

Collapse
No announcement yet.

What is the benefit of using the arrow syntax for a method in a constructor?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • What is the benefit of using the arrow syntax for a method in a constructor?

    What is the benefit of using the arrow syntax for a method in a constructor?



    The main advantage of using an arrow function as a method inside a constructor is that the value of this gets set at the time of the function creation and can't change after that. So, when the constructor is used to create a new object, this will always refer to that object.


    Code:
    const Person = function(firstName) {
    this.firstName = firstName;
    this.sayName1 = function() { console.log(this.firstName); };
    this.sayName2 = () => { console.log(this.firstName); };
    };
    
    const john = new Person('John');
    const dave = new Person('Dave');
    
    john.sayName1(); // John
    john.sayName2(); // John
    
    // The regular function can have its 'this' value changed, but the arrow function cannot
    john.sayName1.call(dave); // Dave (because "this" is now the dave object)
    john.sayName2.call(dave); // John
    
    john.sayName1.apply(dave); // Dave (because 'this' is now the dave object)
    john.sayName2.apply(dave); // John
    
    john.sayName1.bind(dave)(); // Dave (because 'this' is now the dave object)
    john.sayName2.bind(dave)(); // John
    
    var sayNameFromWindow1 = john.sayName1;
    sayNameFromWindow1(); // undefined (because 'this' is now the window object)
    
    var sayNameFromWindow2 = john.sayName2;
    sayNameFromWindow2(); // John


    The main takeaway here is that this can be changed for a normal function, but the context always stays the same for an arrow function. So even if you are passing around your arrow function to different parts of your application, you wouldn't have to worry about the context changing.

Related Topics

Collapse

Working...
X