Home > Web Front-end > JS Tutorial > How Does `this` Keyword Behave Differently in ES6 Arrow Functions Compared to Traditional Functions?

How Does `this` Keyword Behave Differently in ES6 Arrow Functions Compared to Traditional Functions?

Mary-Kate Olsen
Release: 2024-12-21 06:45:11
Original
137 people have browsed it

How Does `this` Keyword Behave Differently in ES6 Arrow Functions Compared to Traditional Functions?

Arrow Functions and This

In ES6, arrow functions offer a concise syntax for defining functions. However, their behavior differs from traditional functions in how they handle the this keyword.

Consider the following code:

var person = {
  name: "jason",
  shout: () => console.log("my name is ", this.name) // Error: This is unbound
};

person.shout();
Copy after login

Here, the intention is to log "my name is jason" when person.shout() is invoked. However, the output is "my name is undefined". This is because arrow functions do not have their own this binding. Instead, they inherit the this value from the enclosing scope.

In this case, the enclosing scope is the global scope, where this refers to the window object. Since the window object does not have a name property, the this.name expression evaluates to undefined.

To resolve this issue, you can utilize the fact that arrow functions do not bind this. By placing the arrow function directly inside the object literal, you can inherit the correct this value from the object:

var person = {
  name: "jason",
  shout: function() {
    console.log("my name is ", this.name)
  }
};

person.shout(); // Output: my name is jason
Copy after login

Alternatively, you can use an ES6 method declaration without the function keyword and : syntax:

var person = {
  name: "jason",
  shout() {
    console.log("my name is ", this.name)
  }
};

person.shout(); // Output: my name is jason
Copy after login

By utilizing these techniques, you can effectively use this within arrow functions and achieve the desired output.

The above is the detailed content of How Does `this` Keyword Behave Differently in ES6 Arrow Functions Compared to Traditional Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template