Here this keyword which is in arrow function points to obj's variable environment
var greeting = 'hi';
const obj = {
greeting: 'hey',
fo() {
const greeting = 'hola';
const arrowFo = () => {
console.log(this.greeting);
};
arrowFo();
},
};
obj.fo(); //logs: hey
var greeting = 'hi';
const obj = {
greeting: 'hey',
fo() {
const greeting = 'hola';
const fo2 = function () {
const greeting = 'hello';
const arrowFo = () => {
console.log(this.greeting);
};
arrowFo();
};
fo2();
},
};
obj.fo(); //logs: hi
Arrow functions have no this value in their scope, so you can access this value of the object. But Normal functions have this value in their scope, in this example this value of the normal function is globalThis or window. and it allows to you access the global scope. if you call fo2 with this value of object instead of globalThis you get '"hey"'
var greeting = 'hi';
const obj = {
greeting: 'hey',
fo() {
const greeting = 'hola';
const fo2 = function () {
const greeting = 'hello';
const arrowFo = () => {
console.log(this.greeting);
};
arrowFo();
};
fo2.call(this) // Use this instead of fo2()
},
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With