自己动手写bind、apply、call,仅展示这三个方法的实现原理,没有处理健壮性:
Function.prototype.myBind=function(){
[thisCtx,...args]=[...arguments];
//非严格模式,当obj为null或undefined时,绑定的this指向全局对象,浏览器环境下是window
thisCtx=thisCtx||window;
args=args||[];
let self=this;
return function () {
let allArgs=args.concat(Array.from(arguments));
self.myApply(thisCtx,allArgs);
}
}
Function.prototype.myApply=function (thisCtx,array) {
thisCtx=thisCtx||window;
thisCtx.fn=this;
array? Array.isArray(array)?thisCtx.fn(...array):console.log('请传入数组参数'):thisCtx.fn();
}
Function.prototype.myCall=function () {
[thisCtx,...args]=[...arguments];
thisCtx=thisCtx||window;
thisCtx.fn=this;
args&&args.length>0?thisCtx.fn(...array):thisCtx.fn();
}
function fn(age) {
console.log(this.name+":"+age);
}
var obj={
name:'zhangsan'
};
(()=>{
let bind=fn.myBind(obj,18);
bind();
})();
//zhangsan:18