Behavior of Arrow functions and Regular Functions for this Keyword
Last Updated :
27 Dec, 2024
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());
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();
OutputHello, 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());
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
Aspect | Regular Functions | Arrow Functions |
---|
Context of this | Defined by how the function is called | Lexically inherited from the parent scope |
---|
Behavior in Methods | this refers to the object calling it | this does not refer to the calling object |
---|
Behavior in Global Context | Refers to global object or undefined in strict mode | Refers to the enclosing context |
---|
Suitable for Callbacks | Needs explicit binding to maintain this | Automatically 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.
Similar Reads
Difference between Regular functions and Arrow functions
Regular functions and arrow functions are two common ways to define functions in JavaScript, each with distinct behaviors. Regular functions offer traditional syntax and this context handling, while arrow functions provide a concise syntax and lexical this binding, making them ideal for callbacks an
6 min read
What is the arrow function, and how to create it ?
Function in any programming language is the basic building block to create and combine the related bits of code. Every programming language provides certain kinds of practices to write any function. The arrow function syntax is one of the most used and efficient ones to create a function in JavaScri
5 min read
How to Declare the Return Type of a Generic Arrow Function to be an Array ?
In TypeScript, declaring the return type of a generic arrow function to be an array is generally essential when we want to ensure that the function always returns the array of a particular type. This is especially necessary for maintaining type safety and maintaining consistency in our code. Declari
3 min read
Explain the differences on the usage of foo between function foo() {} and var foo = function() {}
Here we see the differences on the usage of foo between function foo() {} and var foo = function() {} types of function declarations in JavaScript. function foo() {} is a Normal Function or traditional general way of Function Declaration which every user or developer finds it simpler to declare and
4 min read
Functional Programming: Pure and Impure Functions
Functional programming is a programming paradigm that focuses on the use of functions to solve problems. In functional programming, functions are treated as first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned as values. Pure and impure functions are two
4 min read
How to get Function Parameters from Keys in an Array of Objects Using TypeScript ?
In TypeScript, we can extract the function parameters from keys in an array of objects by going through object properties dynamically. We can use Generics and Type Assertion to get Function Parameters from Keys in an Array of Objects Using TypeScript. Below are the possible approaches: Table of Cont
3 min read
When should one use Arrow functions in ES6 ?
In this article, we will try to understand when should one use Arrow functions in ES6 instead of the traditional function's syntax with the help of some examples. Before analyzing why we should use arrow functions, let us first understand the basic details which are associated with the arrow functio
4 min read
Difference Between Function Overloading and Function Overriding in JavaScript
Function overloading and function overriding are two important concepts in object-oriented programming (OOP). Function overloading allows the creation of multiple functions with the same name but different parameters. Function overriding allows the subclass or child class to provide the specific imp
3 min read
PHP get_defined_functions() Function
The get_defined_functions() function is an inbuilt function in PHP which returns the all defined functions in the array format. Syntax: array get_defined_functions( bool $exclude_disabled = true )Parameters: This function accepts one parameter that is described below: $exclude_disabled: It will chec
2 min read
Can we use Hoisting with Arrow function ?
In this article we will see how does exactly Hoisting works using both normal function as well as arrow function in JavaScript. Arrow function: Arrow function introduced in ES6, provides a concise way to write functions in JavaScript. Another significant advantage it offers is the fact that it does
3 min read