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
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Top 10 Projects For Beginners To Practice HTML and CSS Skills Learning to code is an exciting journey, especially when stepping into the world of programming with HTML and CSSâthe foundation of every website you see today. For most beginners, these two building blocks are the perfect starting point to explore the creative side of web development, designing vis
8 min read