1.call()
The first parameter: this points to
if you want to pass parameters, followed by parameters
function fn(x) {
console.log(x); // 打印的是1
console.log(this.name); // 打印的是小寿司
}
const obj = {
name:"小寿司"
}
fn.call(obj,1); // 此时fn()这个函数this指向obj这个对象,原来fn()这个函数的this指向window
// 原来fn()这个函数内部是没有name这个值,
// 改变this指向后就可以去obj这个对象中找name
2.apply()
The difference from the first method is that the parameters are represented in the form of an array
function fn(x,y){
console.log(x,y); // 打印的是1,2
console.log(this); // 打印的是obj这个对象
console.log(this.name) // 打印的是小寿司
}
var obj = {
name:"小寿司"
}
fn(1,2); //这里执行输出的this是window全局对象,
fn.apply(obj,[1,2]); //改变this指向后,this.name就是小寿司
After running, the console output is as follows:
3.bind()
bind only changes the point of this, and does not call the function (both call and apply)
function fn(x,y){
console.log(x,y);
console.log(this.name)
}
const obj = {
name:"小寿司"
}
fn(1,2);
fn.bind(obj,1,2)(); // 此时若没有后面的小括号,fn()这个函数将不会调用
The difference between call and apply :
The call() method has the same function as the apply() method, the difference is that they receive different parameters.