Lets say I have this code, with normal function:
let a = {
parent: "roger",
child: "bear",
printName: function() {
console.log(`${this.parent} ${this.child}`)
}
}
b = {
parent: "float",
child: "bear",
}
a.printName.call(b)
The output is as expected:
float bear
However, the same code with anonymous function doesn't work:
let a = {
parent: "roger",
child: "bear",
printName: () => {
console.log(`${this.parent} ${this.child}`)
}
}
b = {
parent: "float",
child: "bear",
}
a.printName.call(b)
This results in:
undefined undefined
Even passing 'this' to anonymous doesn't seem to work:
let a = {
parent: "roger",
child: "bear",
printName: (this) => {
console.log(`${this.parent} ${this.child}`)
}
}
This results in a syntax error: Unexpected token this
Questions:
- Please explain why is this happening?
- How to get it to work?