The first thing to note is that the reference of this is not determined at function definition. It is only determined at function execution that this refers to. In fact, this refers to the object calling it

The this pointer is commonly used in the following cases:

Case 1: If a function has this in it, but it is not called by an object at the upper level, then this refers to window. It needs to be noted that in the strict version of JS, this does not refer to Window, but to underpay.

 function test(){
    var name = "John";
    console.log(this.name); //undefined
    console.log(this); //Window
 }
    test();   // Actually window.test();
Copy the code

Case 2: If a function has this and the function is called by a higher-level object, then this refers to the higher-level object.

 var a = {
    name:"CC".b: {name:"John".fn:function(){
            console.log(this.name); //John
            console.log(this); //b
            }
        }
    }
        a.b.fn(); 
        // The upper level is b, which means that b is called, so this refers to the scope of B.
Copy the code

Case 3: Assigning an object to a newly created instance

var a = {
    name:"CC".b: {name:"John".fn:function(){
            console.log(this.name); //undefined
            console.log(this); //window}}}var new = a.b.fn;   // assign the fn function to new
    new(a);//window.new(); Same thing as case 1
Copy the code

Case 4: Constructor, new instance

 function Fn(){
        this.name = "John";
    }
    var a = new Fn();
    console.log(a.name); //John
Copy the code

Here we construct instance A, where the this pointer points to the scope of A, since the upper calling object of name is A. Example A was empty, empty. But we gave it to A by using the constructor new, which is to copy the stuff in Fn to A, so now A has something.