This is the eleventh day of my participation in the August Wen Challenge.More challenges in August

About this

The this keyword is one of the most complex mechanisms in JavaScript. It is a special keyword that is automatically defined in all function scopes. Many of you who are new to JavaScript are just as confused as I am about what this refers to. In fact, this in JavaScript is often confusing because we complicate our understanding process.

To figure out what this is, we have to figure out what this is. This is bound at run time, not at write time, and its context depends on various conditions at the time the function is called. The binding of this has nothing to do with the position of the function declaration, except how the function is called.

When a function is called, its execution context is created. This includes information about where the function is called (the call stack), how the function is called, the parameters passed in, and so on. This is an attribute of the record that is used during function execution. In plain English, this is essentially a binding that occurs when the function is called, and what it points to depends entirely on where the function is called.

The position

Before you understand the binding process for this, it’s important to understand the call location: the call location is where the function is called in the code (not declared). The most important thing to find is to analyze the call stack (that is, all the functions that have been called to reach the current execution location). The call location we care about is in the previous call of the currently executing function. Such as:

     function zijie(){
        // The current stack is :zijie
        // Therefore, the current call location is global scope
        console.log("zijie");
        juejin();     // The call location of juejin
    }
    function juejin(){
        // The current stack is zijie → juejin
        // Therefore, the current call location is in zijie
        console.log("juejin");
        baiqi();    // Call location of baiqi
    }
    function baiqi(){
        // The current stack is zijie → juejin → baiqi
        // Therefore, the current call location is in juejin
        console.log("baiqi");
    }
    zijie();    // Call location of zijie
Copy the code