Hi everyone, I am 梅巴哥er
. This article will talk about the three brothers used to bind this--call, apply, and bind.
call
The syntax of call
function.call(thisArg, arg1, arg2, ...)
call syntax explanation
Just use thisArg, arg1, arg2, ... these parameters to call the function before the call.
call() 提供新的 this 值给当前调用的函数/方法。
among them:
thisArg
It is not necessary. If this function is in non-strict mode and thisArg is null or undefined, it points to the global object.- arg1, arg2, …These are the actual parameters passed into the function.
return value of call
使用调用者提供的 this 值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefined。
Call code example
// example1
function A(name, age) {
this.name = name
this.age = age
this.sayHi = function() {
console.log('Athis: ', this) // 查看A的this指向
}
}
function B() {
A.call(this, '迪丽热巴', 18)
console.log(this) // 查看this指向情况
}
var dili = new B()
console.log(dili.name + '今年' + dili.age + '岁了')
var a = new A()
a.sayHi()
// 输出:B { name: '迪丽热巴', age: 18, sayHi: [Function] }
// 迪丽热巴今年18岁了
// Athis: A { name: undefined, age: undefined, sayHi: [Function] }
// call指定了参数B的this,call给A提供了新的this值
// B通过this和另外两个参数,调用了函数A
// B此时继承了A的属性,所以call可以实现继承
// A.call(),A必须是function类型,不能是其他类型。
Let's look at another example
function a(age) {
console.log('hi, ', this.name + age + '岁了')
console.log(this)
}
obj = {
name: '迪丽热巴'
}
a.call(obj, 18)
// 输出:hi, 迪丽热巴18岁了 { name: '迪丽热巴' }
// obj和参数18通过call调用了函数a
// call给a提供了新的this值obj
apply
apply syntax
func.apply(thisArg, [argsArray])
thisArg
It is a required option.[argsArray]
Is an array- The apply() method is similar to the call() method. The difference is that the call() method accepts a parameter list , while the apply() method accepts an array of parameters .
bind
The bind() method creates a new function. When bind() is called, the this of this new function is specified as the first parameter of bind(), and the remaining parameters will be used as the parameters of the new function for the call.
bind return value
返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。
Bind is often used in projects to bind the this point of event functions.
But after the arrow function is used, there is no need to bind with bind.
Examples of bind binding events
// 为了在回调中使用 `this`,这个绑定是必不可少的
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
This example can be modified like this:
// 这样就不需要再单独绑定this了
handleClick = () => {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
the above.