1.作用
bind call apply的作用都是改变this的指向:以bind举例如下
var obj = {
objName: "my name is tom",
say: function () {
console.log(this.objName);
}
};
var kellyObj = {
objName:"my name is kelly"
}
obj.say(); // my name is tom,this 指向 obj 对象
obj.say.bind(kellyObj)()//"my name is kelly" ,this 指向 kellyObj 对象
2.再来看下三者区别
bind返回的是一个方法this永久生效,需要调用该返回方法才能执行原方法
apply和call则是直接调用原方法,且this只生效一次,区别在于call直接传递参数,apply需要把参数放到数组里传递
var obj = {
objName: "my name is tom",
say: function (age?,city?) {
console.log(this.objName,age,city);
}
};
var kellyObj = {
objName:"my name is kelly"
}
obj.say.bind(kellyObj)(19,"beijing")//"my name is kelly", 19, "beijing" ,this 指向 kellyObj 对象
obj.say.apply(kellyObj,[19,"beijing"])//"my name is kelly", 19, "beijing" ,this 指向 kellyObj 对象
obj.say.call(kellyObj,19,"beijing")//"my name is kelly", 19, "beijing" ,this 指向 kellyObj 对象
3.实现一个apply,另外两个同理,核心思想就是“this”指向谁,就在谁的结构里加一个方法,调用完毕后再删掉这个方法
Function.prototype.myApply = function (context: any, args: any[] = []) {
if (!context) context = globalThis
if (typeof context !== 'object') context = new Object(context) // 值类型转化为对象
const fnKey = Symbol()
context[fnKey] = this // this 就是当前的函数
const res = context[fnKey](...args) // 绑定了this 这是立即执行
delete context[fnKey]
return res
}
let obj = {
name:"tom",
say:function(param,param2){
console.log(param,param2,this.name)
}
}
let kellyObj = {
name:"kelly"
}
obj.say.myApply(kellyObj,["abc","def"])//"abc", "def", "kelly"