This points to the problem and the usage and difference of call, apply and bind

this points to the question

1. Ordinary functions

1.1 Ordinary non-anonymous function: Whoever calls the function or method, then this in this function or object points to whom

let getThis = function () {
    
    
  console.log(this);
}

let obj={
    
    
  name:"Jack",
  getThis:function(){
    
    
    console.log(this);
  }
}
//getThis()方法是由window在全局作用域中调用的,所以this指向调用该方法的对象,即window
getThis();//window
//此处的getThis()方法是obj这个对象调用的,所以this指向obj
obj.getThis();//obj

1.2 Ordinary anonymous function: the execution of the anonymous function is global, so the this in the anonymous function points to the window, not the object calling the anonymous function

let obj = {
    
    
  getThis: function () {
    
    
     return function () {
    
    
       console.log(this);
     }
   }
}

obj.getThis()(); //window

In the above code, the getThi() method is called by obj, but obj.getThis() returns an anonymous function, and this in the anonymous function points to window, so window is printed out. If you want to make this point to the object calling the method in the above code, you can pass this value to another variable (_this or that) in advance:

let obj = {
    
    
  getThis: function () {
    
    
  	//提前保存this指向
  	let _this=this
  	return function () {
    
    
      console.log(_this);
  	}
  }
}

obj.getThis()(); //obj

2. Arrow functions

  • The this in the arrow function is determined when the function is defined, not when the function is called;
  • This in the arrow function points to the execution context of the parent scope; (tip: because in javascript, except for the global scope, other scopes are created by functions, so if you want to determine the direction of this, find the closest to the arrow function function, the this in the execution context at the same level as the function is the this in the arrow function)
  • Arrow functions cannot use the apply, call, and bind methods to change the direction of this, because the value of this is determined when the function is defined.

2.1 Find the nearest function: First, the closest function to the arrow function is getThis(){}, and the execution context parallel to this function is the execution context in obj. The this in the arrow function is the this in the commented code, that is obj.

let obj = {
    
    
  //此处的this即是箭头函数中的this
  getThis: function () {
    
    
    return  ()=> {
    
    
      console.log(this);
    }
  }
}
obj.getThis()(); //obj

2.2 Cannot find function: There are two arrow functions in this code, and this cannot find the corresponding function(){}, so I keep searching until it points to window.

//代码中有两个箭头函数,由于找不到对应的function,所以this会指向window对象。
let obj = {
    
    
  getThis: ()=> {
    
    
     return  ()=> {
    
    
       console.log(this);
     }
   }
}
obj.getThis()(); //window

call、apply和bind

Effect:
Both can change the this pointer inside the function.

Differences:

  1. call and apply will call the function immediately and change the internal this point of the function.
  2. The parameters passed by call and apply are different, call passes parameters arg1, arg2... form, apply must be in the form of an array [arg]
  3. bind will not call the function immediately, but can change the internal this point of the function, and pass parameters in the form of arg1, arg2....

Main application scenarios:

  1. call often does inheritance.
  2. apply is often related to arrays, such as realizing the maximum and minimum values ​​of an array with the help of mathematical objects.
  3. bind does not call the function, but still wants to change the this point, such as changing the this point inside the timer.

The call method:
change the internal this point of the function. The call() method calls an object, which is simply understood as the way to call the function. It can change the this point of the function.
Writing method: fun.call(thisArg, arg1, arg3, …), thisArg is the object you want to point to, arg1, arg3 are the parameters. The
main function of call can also achieve inheritance

  function Person(uname, age) {
    
    
    this.uname = uname;
    this.age = age;
  }
  function Son(uname, age) {
    
    
    Person.call(this, uname, age);
  }
  var son = new Son("zhang", 12);
  console.log(son);

apply method:
The apply() method calls a function, which is simply understood as the way to call a function, which can change the this point of the function.
Writing method: fun.apply(thisArg, [argsArray]), thisArg: the this value specified when the fun function is running, argsArray: the passed value must be included in the array, and the return value is the return value of the function, because it is the calling function .
The main application of apply, for example, you can use apply to find the maximum value in the array

const arr = [1, 22, 3, 44, 5, 66, 7, 88, 9];
const max = Math.max.apply(Math, arr);
console.log(max);

bind method:
The bind() method will not call the function immediately, but it can change the internal this point of the function
Writing method: fun.bind(thisArg, arg1, arg2, ...), thisArg: the this value specified when the fun function is running, arg1, arg2 : Other parameters passed.
Returns a copy of the original function modified by the specified this value and initialization parameters

var o = {
    
    
    name: "lisa"
};
function fn() {
    
    
    console.log(this);
}
var f = fn.bind(o);
f();

Bind application
If there is a function that we don't need to call immediately, but needs to change the this point of this function, it is more appropriate to use bind at this time, such as the use of timers.

const btns = document.querySelectorAll("button");
for (let i = 0; i < btns.length; i++) {
    
    
    btns[i].onclick = function() {
    
    
      this.disabled = true;
      setTimeout(
        function() {
    
    
          this.disabled = false;
        }.bind(this),
        2000
      );
    };
}

Guess you like

Origin blog.csdn.net/qq_45488467/article/details/128931628