I have a doubt when I tried to access global variable in two functions. One function is an arrow function another function is a normal function. The arrow function is working fine, but the normal function cannot a print global variable. Why?
Example Code
class Data1{
constructor(m1){
this.m1 = m1
}
}
class Data2 extends Data1{
func1(){
console.log(this.m1)
this.m1 = 20
}
func2=()=>{
console.log(this.m1)
this.m1 = 40
}
}
d1 = new Data1(10)
d2 = new Data2()
d2.func1()
d2.func2()
Output
undefined
20
In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.
With arrow functions the this keyword always represents the object that defined the arrow function.
If you write a constructor in Data1 and bind func1 to the Data1 object it will work. For eg.
constructor(){
this.func1 = this.func1.bind(this);
}