这段代码有什么作用?

时间:2011-09-02 23:16:30

标签: javascript

Function.prototype.bind = function() {
    var _this = this,
        original = _this,
        args = Array.prototype.slice.call(arguments),
        _obj = args.shift(),
        func = function() {
            var _that = _obj;
            return original.apply(_that, args.concat(
            Array.prototype.slice.call(
            arguments, args.length)));
        };
    func.bind = function() {
        var args = Array.prototype.slice.call(arguments);
        return Function.prototype.bind.apply(_this, args);
    }
    return func;
};

我知道这是一个绑定功能。但我不明白它和它在做什么,特别是args.concat部分。 concat做了什么?此外,.bind.apply不能.call方法做什么?

2 个答案:

答案 0 :(得分:3)

bind函数接受一个函数,并确保它始终绑定到特定的this值。最简单的例子是事件处理程序。默认情况下,事件处理程序的this值绑定到window。但是,假设您要将对象的方法用作侦听器,并在该侦听器中更改某些属性:

var thing = {
    answer : 4,
    listener : function() {
        this.answer = 42;
    }
}
window.onload = thing.listener;

在onload事件中,thing.answer现在不是window.answer,而是bind现在是42.所以,我们使用window.onload = thing.listener.bind(thing);

bind

因此,this返回一个函数,该函数在调用时调用原始函数,但具有指定的[].concat值。

[].concat(5, 4)只是将参数添加到数组中 - 因此[5, 4]返回[5, 4].concat([42])[5, 4, 42]返回bind。在这种情况下,它用于连接参数 - 您可以将参数传递给{{1}}函数,该函数在调用函数时将作为参数传递。连接的工作方式是,当您调用绑定函数时,您传递的参数也会被传递。

答案 1 :(得分:2)

shim似乎是Function.bind()

  

但我不理解它以及它正在做什么,特别是args.concat部分。 concat做了什么?

Array.concat()将两个或更多Array个(以及其他值连接到Array)。

  

此外,.bind.apply不能.call方法做什么?

它返回对this绑定到你想要的任何函数的函数的引用。

var newFn = fn.bind(['a', 'b', 'c']);

// This will call `fn()` with the above `Array` as `this`.
newFn('first arg', 'second arg'); 

对于卷曲,例如,它是有用的。返回一个已设置参数的函数(除了在this中设置bind()之外,您可以设置默认参数。)