Open In App

Behavior of Arrow functions and Regular Functions for this Keyword

Last Updated : 27 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, the behavior of the this keyword differs between arrow functions and regular functions.

  • The this keyword in Arrow Functions is lexically bound, meaning it takes the value of this from the surrounding context where the function was defined, not where it's called.
  • In Regular Functions, this is dynamically bound based on how the function is called (e.g., in an object method, this refers to the object).

this in Regular Functions

Regular functions define their own context for this based on how they are called. It refers to the object that is invoking the function, or the global object (in non-strict mode) if the function is called in a global context

1. Method Context: When a regular function is called as a method of an object, this refers to the object that owns the method.

JavaScript
const obj = {
    name: "Object",
    getName: function() {
        return this.name;
    }
};
console.log(obj.getName());

Output
Object
  • obj is an object with a property name and a method getName.
  • getName uses this.name to return the value of the name property.
  • When obj.getName() is called, this inside the method refers to the obj object.
  • The method returns "Object", which is the value of obj.name.

2. Standalone Function Context: When a regular function is called as a standalone function, this refers to the global object (window in browsers, global in Node.js). In strict mode, this is undefined.

JavaScript
function showThis() {
    console.log(this);
}
showThis(); 

Output
<ref *1> Object [global] {
  global: [Circular *1],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Functio...
  • showThis() logs the value of this.
  • In non-strict mode, this refers to the global object (e.g., window in browsers).
  • In strict mode, this is undefined inside the function.

Dynamic Binding: Regular functions allow the value of this to be explicitly set using methods like call, apply, or bind.

JavaScript
// Regular function
function greet() {
    console.log(`Hello, my name is ${this.name}`);
}

// Object with a name property
const person = {
    name: 'GFG'
};

// Using call to explicitly set the value of 'this'
greet.call(person); 

// Using apply (similar to call, but accepts arguments as an array)
greet.apply(person);

// Using bind to explicitly set the value of 'this' and return a new function
const greetings = greet.bind(person);
greetings(); 

Output
Hello, my name is GFG
Hello, my name is GFG
Hello, my name is GFG
  • call: It invokes the greet function and explicitly sets this to the person object.
  • apply: Similar to call, but arguments are passed as an array (here no additional arguments are passed).
  • bind: It returns a new function where this is permanently bound to the person object. The new function (greetAlice) can be called later.

this in Arrow Functions

Arrow functions, introduced in ES6, behave differently. They do not define their own this context. Instead, they inherit this from the surrounding lexical scope at the time of their creation.

1. Lexical Scoping: In an arrow function, this is determined by the context in which the function is defined, not where it is called.

JavaScript
const obj = {
    name: "Object",
    getName: () => this.name
};
console.log(obj.getName());

Output
undefined

Here,this refers to the global object because the arrow function does not bind its own this.

2. Useful in Callbacks: Arrow functions are particularly useful in callbacks, where you want to preserve the this context of the enclosing scope.

JavaScript
function Timer() {
    this.seconds = 0;
    setInterval(() => {
        this.seconds++;
        console.log(this.seconds);
    }, 1000);
}
const timer = new Timer();


The arrow function inside setInterval inherits this from the Timer constructor, ensuring it refers to the Timer instance.

Key Differences

AspectRegular FunctionsArrow Functions
Context of thisDefined by how the function is calledLexically inherited from the parent scope
Behavior in Methodsthis refers to the object calling itthis does not refer to the calling object
Behavior in Global ContextRefers to global object or undefined in strict modeRefers to the enclosing context
Suitable for CallbacksNeeds explicit binding to maintain thisAutomatically preserves this context

Note: Difference between Regular functions and Arrow functions

Best Practices

  • Understand the Context: Always be aware of the scope in which your function operates. Use regular functions for scenarios requiring dynamic this binding and arrow functions for consistency with the enclosing lexical scope.
  • Choose the Right Function Type: Use regular functions in object methods or when using inheritance in classes. Use arrow functions in callbacks, event handlers, or higher-order functions.
  • Avoid Using Arrow Functions as Methods: Since arrow functions do not have their own this, avoid using them in object methods if you need this to refer to the object.
  • Leverage Tools and Linters: Use tools like ESLint to enforce consistent and appropriate use of function types in your codebase.

Next Article
Article Tags :

Similar Reads