不说太多,直入主题
由浅入比浅深一点
先创建一点公有数据
function test (str){
console.log(str+this.name)
}
let obj = {
name:'This'
}
首先说点这三者的不同点
- call与apply两个是立即执行的,而bind会返回一个函数
- call与bind的传参方式相同,而apply除开第一个所传所需this的对象外,是以数组的方式传参
- call,apply,bind实现的作用相同,但是本质区别是bind不会改变原函数的this指向
- …(才疏学浅,欢迎补充与建议)
call实现
实现步骤
- 在Function的原型链上实现该方法(…arges区别与apply,将所传参数解构)
- 只在函数上实现该功能
- 确定所传对象有效
- 将当前函数this绑定到该对象上
- 执行该对象绑定的此函数
Function.prototype.mycall = function(context,..arges){//与apply不同
if(typeof this !== 'function'){
throw new TypeError(`${this} is not function`)
}
const Context = Object(context)||window;//防止传入的context为null或是undefined
Context.fn = this;
Context.fn(...arges)
delete Context.fn
}
test.mycall(oobj,'mycall -')//mycall -This
apply实现
实现步骤
- 在Function的原型链上实现该方法(arges区别与call)
- 只在函数上实现该功能
- 确定所传对象有效
- 将当前函数this绑定到该对象上
- 执行该对象绑定的此函数
Function.prototype.myapply = function(context,arges){//与call不同
if(typeof this !== 'function'){
throw new TypeError(`${this} is not function`)
}
const Context = Object(context)||window;//防止传入的context为null或是undefined
Context.fn = this;
Context.fn(...arges)
delete Context.fn
}
test.myapply(oobj,['myapply -'])//myapply -This
bind实现
绑定this指向
返回一个绑定后的函数(高阶函数原理)
如果绑定的函数被new执行 ,当前函数的this就是当前的实例
new出来的结果可以找到原有类的原型
完整版bind分别使用mycall与myapply
//内部利用了mycall
Function.prototype.mybind = function(context,...arges){
let that = this;
let bindFn = function(...otherArges){
let isNew = this instanceOf bindFn
let Context = isNew?this:(Object(context)||window);//防止传入的context为null或是undefined
return that.mycall(Context,...arges,...otherArges)
}
bindFn.prototype = that.prototype;
return bindFn;
}
let testFn = test.mybind(obj,'mybind -')
testFn()//mybind - This
//内部利用了myapply
Function.prototype.mybind = function(context,...arges){
let that = this;
let bindFn = function(...otherArges){
let isNew = this instanceOf bindFn
let Context = isNew?this:(Object(context)||window);//防止传入的context为null或是undefined
return that.myapply(Context,arges.concat(otherArges))
}
bindFn.prototype = that.prototype;
return bindFn;
}
let testFn = test.mybind(obj,'mybind -')
testFn()//mybind - This
总结
关键的实现步骤,怎么实现函数可以直接调用与怎么把this绑定到所传对象上。同时还要区别与这三种方式不同点。
欢迎指正批评!!!