Home > Web Front-end > JS Tutorial > body text

Arrow function and this

PHPz
Release: 2024-07-31 01:28:24
Original
827 people have browsed it

Arrow function and this

What would be the result of this foo.baz()??

const foo = {
  bar: 10,
  baz: () => console.log(this.bar),
};


foo.baz();

Copy after login

This function looks like it should work but if you run this, the result will be “undefined”. Why so?
In JavaScript, when you use an arrow function, the function console.log(this.bar) will look for a global variable, because “this” keyword is not bound to the surrounding object but a global object (window) in the browser or node.js environment.
In order to fix this issue we either use foo.bar or change a code a little and use regular function expression like so

 baz: function () {
    console.log(this.bar);
  },

Copy after login

Or if we have to use an arrow function, instead of calling a local variable as this.bar, we can use object name and call foo.bar like so .

 baz: () => console.log(foo.bar),

Copy after login

Now the output will be correctly 10.

The above is the detailed content of Arrow function and this. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!