Reputation: 303
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
Upvotes: 9
Views: 10078
Reputation: 1659
In JavaScript the this object is really based on how you make your function calls. the fo2() function is not binded in any object for this purpos it get the this of global context
you have to declare your function with the this like this :
var greeting = 'hi';
const obj = {
greeting: 'hey',
fo() {
const greeting = 'hola';
this.fo2 = function () {
const greeting = 'hello';
const arrowFo = () => {
console.log(this.greeting);
};
arrowFo();
};
this.fo2();
},
};
obj.fo(); //logs: hi
or use arrow function like this :
var greeting = 'hi';
const obj = {
greeting: 'hey',
fo() {
const greeting = 'hola';
fo2 = () => {
const greeting = 'hello';
const arrowFo = () => {
console.log(this.greeting);
};
arrowFo();
};
fo2();
},
};
obj.fo();
Upvotes: 2
Reputation: 136
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()
},
};
Upvotes: 8