The this of a normal function refers to the caller this, which is the object of the call

function fun(){ console.log(this); //window } fun(); / / is equal to the window. The fun ();Copy the code

The constructor

let P=function (){ console.log(this); } P.prototype.funB=function (){ console.log(this) } let p1=new P(); // Both this and this refer to p1.funb ()Copy the code

Arrow functions Arrow functions do not have this or the arrow function’s this points to the outer function’s this, and the arrow function’s this cannot be changed by changing the outer function’s this

var obj2={ say: function (){ let fn= ()=>{ console.log(this); //obj2 } fn() } }Copy the code

Change the function’s this pointer

Call method

function.call(thisArg, arg1, arg2, ...) ; // Parameter 1: the object to which this refers. If null or undefined, it refers to windowCopy the code

The apply method

Func. Apply (thisArg, [argsArray]) // Argument 1:this points to the object, null and undefined point to window // Argument 2: type is data, array elements are function argumentsCopy the code

The bind method

Bind (thisArg[, arg1[, arg2[,...]]]) // thisArg[, arg1[, arg2[,...]]Copy the code
Function say(age){console.log(this,age)} say.call(obj,18); //this refers to obj, age is 18 say.apply(obj,[18]); //this refers to obj, age is 18 let bindFun=say.bind(obj,18); bindFun(); ////this points to obj with an age of 18Copy the code

The arrow function’s this cannot be changed

let fun3=(age)=>{ console.log(this,age) } fun3.call(obj,18); // If you want the arrow function's this to change, change the outer functionCopy the code

It’s over. Wake me up if there’s a mistake. Wake me up if there’s a mistake