Home >Web Front-end >JS Tutorial >How Does the 'this' Keyword Differ Between Arrow Functions and Regular Functions in JavaScript?
Arrow Functions and Context-less "This"
In ES6, arrow functions provide a concise syntax for function declaration. However, one key difference between arrow functions and traditional functions is their handling of the "this" keyword.
When you use an arrow function inside an object as shown in the given code:
var person = { name: "jason", shout: () => console.log("my name is ", this.name) }
The "this" keyword within the arrow function does not refer to the "person" object. Instead, it points to the scope where the arrow function was created, which in this case is the global scope. Therefore, when calling "person.shout()", it logs "my name is" without the "jason" property.
To resolve this issue, you can use regular function syntax instead of an arrow function:
var person = { name: "jason", shout: function() { console.log("my name is ", this.name) } }
In regular functions, "this" refers to the object that owns the function. Therefore, it will correctly output "my name is jason" when called.
Alternatively, you can take advantage of the ES6 method declaration syntax, which is similar to the arrow function syntax:
var person = { name: "jason", shout() { console.log("my name is ", this.name) } }
With this syntax, the function declaration omits the colon (:) and the "function" keyword. However, it still uses the regular function declaration syntax, ensuring that "this" bound to the object.
The above is the detailed content of How Does the 'this' Keyword Differ Between Arrow Functions and Regular Functions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!