js 实现 bind() 函数

// bind() 传参数值有两种方式 
// 1. 直接传值
foo.bind('obj', 1, 2, 3, 4);
// 2.二次传值
var bar = foo.bind('obj', 1, 2);
bar(3, 4)

function foo(num1, num2, num3, num4) {
    return console.log(this, 20);
}

// js实现,bind()函数中返回值是一个函数
Function.prototype.hyBind = function(thisArg, ...argArray) {
    // 1.获取到真实需要调用的函数:获取当前this指向
    var fn = this;
    // 2.绑定this,不存在 指向 window
    //@param thisArg — An object to which the this keyword can refer inside the new function.
    thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window;
    // 二次调用传值
    function proxyFn(...argArr) {
        thisArg.fn = fn;
        var result = thisArg.fn(...[...argArray, ...argArr])
        delete thisArg.fn
        return result
    };
    return proxyFn;
};

// 直接调用
var result1 = foo.hyBind('obj', 1, 2, 3, 4); // 隐式调用:this -> foo
result1();

// 二次调用
var bar = foo.hyBind('obj', 1, 2);
var result2 = bar(3, 4);
result2();

// 原生调用
var result3 = foo.bind('obj', 1, 2, 3, 4);
result3()
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容