I have this code
var key = "outer value";
let obj = {
key:"obj value",
func:()=> this.key,
}
console.log(obj.func());
But when the var is changed to let, the result is undefined. Please guide.
I have this code
var key = "outer value";
let obj = {
key:"obj value",
func:()=> this.key,
}
console.log(obj.func());
But when the var is changed to let, the result is undefined. Please guide.
let key = "outer value";
let obj = {
key:"obj value",
func:()=> key,
}
console.log(obj.func()); //--> Outer Value
var key = "outer value";
let obj = {
key:"obj value",
func:()=> key,
}
console.log(obj.func()); //--> Outer Value
The answer would be same even if this keyword is not used
var key = "outer value";
let obj = {
key:"obj value",
func:()=> key,
}
console.log(obj.func());
An arrow function does not have its on this, It always uses parent this
Your code works because the key is global scope(this)
let key = "outer value";
let obj = {
key:"obj value",
func:()=> key,
}
console.log(obj.func());
This will not work because key is local scope not inside this
function test() {
var key = "outer value";
let obj = {
key: "obj value",
func: () => this.key,
};
console.log(obj.func()); // undefined
}
test();
This Will work
function test() {
this.key = "outer value";
let obj = {
key: "obj value",
func: () => this.key,
};
console.log(obj.func()); // outer value
}
test();