[JavaScript] Function.prototype.bind

每个函数都有一个bind方法,这个方法用来设置该函数的this指向。
例如:

function test(){
    alert(this);
}

test();         //[object Window]
test.call(1);       //1
test.bind(2)();     //2

注:
(1)test.bind(2)返回一个this指向2的函数

在使用test.bind的时候容易出现一个问题,
<u></u>test.bind本来是指向Function.prototype.bind的,
但如果test.bind被用户重定义了,就有问题了。

解决办法是,尽量使用Function.prototype.bind.call(test,2);来设置this指向。

(2)bind实际上返回了一个新函数

Function.prototype.bind=function(thisValue){
    var fn=this;

    return function(){
        return fn.apply(thisValue,arguments);
    };
};

(3)bind支持Currying

fn.bind(thisArg[, arg1[, arg2[, ...]]])

arg1,arg2,...会传入fn,当做fn的前n个参数,并返回一个接受剩余参数的新函数。

Function.prototype.bind=function(thisValue){
    var fn=this,
        partialArgs=[].slice.call(arguments,1);

    return function(){
        return fn.apply(thisValue,[].concat.apply(partialArgs,arguments));
    };
};

例:把附加参数放在arguments前面作为新参数列表调用函数

function f(){
    
    //传递this和arguments
    //return g.apply(this,arguments);

    //传递this和附加参数加上arguments
    return g.bind(this,arg).apply(null,argumetns);
}

规范:
ES 5.1

兼容性:
Basic support
Chrome 7
Firefox (Gecko) 4.0
Internet Explorer 9
Opera 11.60
Safari 5.1

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容