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!