this in the es6 class class points to

this points to

     If there is this inside the method of the class, it will point to the instance of the class by default. However, when using this method alone, it is likely to report an error.

class Logger{
    printName(name = 'there'){
        this.print(`hello ${name}`);
    }
    print(text){
        console.log(text);
    }
}

const logger = new Logger(); //Instantiate
const {printName } = logger;    //printName
printName(); // 报错    VM77:3 Uncaught TypeError: Cannot read property 'print' of undefined

This in the printName method points to the instantiated object of the Logger class by default, but when used alone, this will point to the environment pointed to when the method runs (is the running environment at this time window? I added the print method under the window) After that, the same error is reported (___________)), because the print method cannot be found and an error is reported.


solution:

   1. Bind this in the constructor, so that this will point to the current instance when instantiated

class Logger{
    constructor(){
        this.printName = this.printName.bind(this);
    }

//...
}

    2. Use arrow functions

    

class Logger{
    constructor(){
        this.printName = (name = 'there') => {
            this.print(name);
        }
    }
}

    3. Using Proxy , when getting a method, automatically bind this

    (I will add it when I look back at Proxy)

function selfish(target){
    const cache = new WeakMap();
    const handler = {
            




    }
}







Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324615783&siteId=291194637