来源: 吾推网
发布时间: 2021-08-16
次浏览
call、apply、bind都是改变this指向的方法
首先call与apply的区别是call接收多个参数,apply接收一个数组
如:func.call(newThis, a, b) // newThis表示需要重新指向的this,a,b为函数的参数
如果newThis为{test: "我是新的this对象"},则func的this就指向了{test: "我是新的this对象"}
apply与call相似
func.call(newThis, [a, b]) 只是a,b等参数是放在数组里面
bind也是接收多个参数,和call、apply不同的是它是返回一个函数
如:var f1 = func.bind(newThis, a, b)
f1()
bind的实现
let self = this
let temp = function (...arg2) {
self.apply(thisArg, [...arg1, arg2])
}
temp.prototype = Object.creat(self.protopyte)
temp.custructor = self
return temp
}