I was looking for examples of how “this” works and found this example:
function foo() {
return {
x: 20,
bar: () => {
console.log(this.x);
},
baz: function () {
console.log(this.x);
}
};
}
const obj2 = foo.call({ x: 30 });
let y = obj2.bar;
let z = obj2.baz;
y(); // Output: 30
z(); // Output: undefined
I roughly understand why it gives such a result, but then I’ve tried to modify this example and and set the value to this.x inside the function and remove .call().
function foo() {
this.x = 50;
return {
x: 20,
bar: () => {
console.log(this.x);
},
baz: function () {
console.log(this.x);
}
};
}
const obj2 = foo();
let y = obj2.bar;
let z = obj2.baz;
y(); // Output: 50
z(); // Output: 50
Can someone explain why it works this way?