Here is a sample of Javascript Object using traditional function definition
const obj = {
a: 10,
b: 20,
add: function(){
return this.a + this.b;
}
}
obj.add() // returns 30
When I use arrow function in add, the context of this
in add changes to global i.e. windows
object in browser.
const obj = {
a: 10,
b: 20,
add: () => {return this.a + this.b}
}
obj.add() // this context is global(windows) of it returns NaN
So in order to bind the context back to obj, I implemented call as below:
obj.add.call(obj) // Still the context is global(windows) and returns NaN
So 2 things that I didn't understand is:
- Why didn't the arrow function bind
obj
context by default as in traditional function definition? - Why didn't the
obj
's add method get bind to theobj
even if I've passed it explicitly?