简体   繁体   中英

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?

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

On the line:

d2 = new Data2()

You are calling the constructor of Data1 without any arguments. m1 will be undefined. You will need to pass an argument to the constructor of Data1. This will be done automatically by passing an argument to Data2.

d2 = new Data2(10);

This should solve your problem.

The result is not related to the scope of functions(arrow functions), even not the the this binding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM