bind、call、apply的手动实现

96 阅读1分钟

//new执行的操作 var a = new A(x,y);

var a = new Object();
a._proto_ = A.prototype;
a = A.call(a,x,y);
return a;
  • bind方法
/**
 * 改变方法的指向;
 * 返回绑定this的函数;
 * 接受柯里化传参
 */
Function.prototype.myBind = function(context){
    if( typeof this !== "function") {
        return false;
    }
    let fn = this;
    let args = Array.prototype.slice.call(arguments,1);
    return function(){
        return fn.apply(context,args.concat(Array.prototype.slice.call(arguments)));
    }
}
  • call方法
/**
 * 接收参数为多个且第一个参数为指向的对象;
 * 改变函数this指向;
 * 执行函数;
 * 若无对象参数默认指向window
*/
Function.prototype.myCall = function(context,...args){
    context = context || window;
    let fn = Symbol(context);
    context[fn] = this;
    let result =  context.fn(...args);
    delete context.fn;
    return result;
}
  • apply方法
/**
 * 接收参数为对象和数组;
 * 改变函数this指向;
 * 执行函数;
 * 若无对象参数默认指向window
 */
Function.prototype.myApply = function(context,[...args]) {
    context  = context || window;
    let fn = Symbol(context);
    context[fn] = this;
    let result = context.fn(...args);
    delete context.fn;
    return result;
}