Briefly answer

  • Change this to the bind, call, apply, new operators, arrow functions

1. The direction of this is not determined when the function is created, but only when the function is called

Var o = {function(){console.log(this.log); var o = {function(){console.log(this.log); // Who are you}} o.fein ();Copy the code

2. General situation:

(1) If a function has this, but it is not called by a higher-level object, then this refers to the window

(2) If a function has this, and the function is called by a higher-level object, then this refers to the higher-level object

(3) If a function has this, it contains more than one object. Even though this function is called by the outermost object, this refers to only the object above it

var o = {
    a:10,
    b:{
        a:12,
        fn:function(){
            console.log(this.a); //12
        }
    }
}
o.b.fn();
Copy the code

3. Special case: This always refers to the object that last called it, i.e., who called it when it was executed

var o = {
    a:10,
    b:{
        a:12,
        fn:function(){
            console.log(this.a); //undefined
            console.log(this); //window
        }
    }
}
var j = o.b.fn;
j();
Copy the code

The constructor version of this: object A can point to the user in Fn because the new keyword changes the direction of this

Function Fn(){this.user = this.user; } var a = new Fn(); console.log(a.user); / / who you areCopy the code

5. When this hits return

If the return value is an object, this refers to the returned object. If the return value is not an object, this refers to an instance of the function. Null is also an object, but in this case this refers to an instance of that function because NULL is special.

Function fn(){this.user = 'this.user '; return null; } var a = new fn; console.log(a.user); / / who you areCopy the code