개발javascript

Differences retain context between arrow function and regular function

class Test {
  constructor() {
    this.func1 = () => {
      // use keyword 'this' on the event handler
    }
  }

  func2() {
    // doesn't use keyword 'this' on the event handler
  }
}

The differences between func1 and func2 in the provided JavaScript code relate to how they handle the context of the this keyword. Let’s break down the differences step by step.

  1. **Arrow Function vs Regular Function:** func1 is defined using an arrow function (() => { ... }), whereas func2 is defined using a regular function (function() { ... }). Arrow functions capture the surrounding context, including the value of this, while regular functions have their own this binding that is determined by how the function is called.

  2. **Binding of this:** In func1, since an arrow function is used, the value of this inside func1 will refer to the instance of the Test class where func1 is defined. This means that no matter where func1 is called, the this context remains the same as the instance of the class. Arrow functions don’t have their own this context; they inherit it from their enclosing function (or in this case, the constructor). In func2, since a regular function is used, the value of this will depend on how func2 is called. If func2 is called as a method of the Test instance (testInstance.func2()), then this will refer to the instance. However, if func2 is extracted and called in a different context (e.g., as a standalone function), the value of this can change, possibly leading to errors or unintended behavior.

  3. **Usage in Event Handlers:** If you intend to use these functions as event handlers, func1 might be more convenient. Since it’s an arrow function, it retains the instance context, ensuring that you can use the this keyword inside the event handler to refer to the instance of the class. On the other hand, if you use func2 as an event handler, the value of this might change based on how the event is triggered, potentially leading to unexpected results or errors.

In summary, the key difference between func1 and func2 lies in how they handle the this keyword, with func1 using an arrow function to maintain the instance context and func2 relying on the standard function’s this binding, which can be influenced by how it’s called.