// js中call,apply,bind的实现原理()
// 三者的区别,都是改变this指针,call和apply主要是参数区别,bind返回的是一个函数体,而call和apply是立即执行
// call的实现
function fn1 (str1,str2,str3){
console.log(this,str1,str2,str3);
}
function fn2(){

}
Function.prototype.call = function (context){
    // 避免传入的是基本类型,使用object进行对象化
    context = context ? Object(context) : window;
    context.fn = this;
    let args = [];
    for (let i = 1;i<arguments.length;i++) {
        args.push('arguments[' + i + ']');
    }
    // es数组的结构
    let r = eval("context.fn("+args + ")");
    delete context.fn;
    return r;
}
fn1.call('hellow',1,2,3);

// apply的实现原理
Function.prototype.apply = function (context,args){
// 避免传入的是基本类型,使用object进行对象化
context = context ? Object(context) : window;
context.fn = this;
if (args) {
return eval("context.fn("+args + ")");
}
let argss = [];
for (let i = 1;i<arguments.length;i++) {
argss.push('arguments[' + i + ']');
}
// es数组的结构
let r = eval("context.fn("+args + ")");
delete context.fn;
return r;
}
fn1.apply('hellow',[1,2,3]);
//bin的实现的话,改变函数不要立即执行就可以

posted on 2020-03-04 02:48  IT猩  阅读(526)  评论(0编辑  收藏  举报