Search code examples
javascripttypescriptjavascript-objectstypescript1.8

How to global variable access in function using Javascript?


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
  • What is difference between normal scope function and arrow scope function?
  • How to access global function inside the normal function?

Solution

  • 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);
    }