Home  >  Article  >  Web Front-end  >  Arrow function and this

Arrow function and this

PHPz
PHPzOriginal
2024-07-31 01:28:24806browse

Arrow function and this

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

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


foo.baz();

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);
  },

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),

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!

Statement:
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