1. I am calling a function myDes()
which is an Arrow Function inside
an Object Cameras
. It is returning undefined
.
2. But when I call the function myDes()
from a Class instance obj1
it returns a string - "abc"
.
In my understanding arrow function binds by default the properties of the parent function or the global scope, then why does it not return the price in the first example as it does name in the second?
Example 1 — Calling from an Object
const cameras = {
price: 600,
weight: 2000,
myDes: () => {
return `This canon camera is of ${this.price}`
}
}
console.log(cameras.myDes()) // price undefined
Example 2 — Calling from an Instance of a Class
class Student {
name = 'abc'
myDes = () => {
console.log(this.name)
}
}
let obj = new Student
obj.myDes() // return abc
*
To the Comments Below suggesting some link reference for answers. What I meant since there is no parent function around the arrow function in the Class then how the arrow function is inheriting the properties of the class. To which a satisfied answer has been provided