简体   繁体   中英

What does this code do?

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;
};

I know it's a bind function. But I don't understand it and what it's doing, specifically the args.concat part. What does concat do? Also, what does .bind method do that .apply and .call can't?

The bind function takes a function and ensures that it is always bound to a specific this value. The easiest example is in event handlers. By default, event handler's this value is bound to window . However, let's say that you want to use an object's method as a listener, and in that listener change some properties:

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

On the onload event, instead of thing.answer being changed like intended, window.answer is now 42. So, we use bind :

window.onload = thing.listener.bind(thing);

So, bind returns a function, that when called, calls the original function, but with the specified this value.

[].concat simply adds the arguments to the array - so [].concat(5, 4) returns [5, 4] , and [5, 4].concat([42]) returns [5, 4, 42] . In this case, it is used to concatenate arguments - you can pass arguments to the bind function that'll be passed as arguments when the function is called. The concatenation works so that when you call the binded function, the arguments you pass now are also passed along.

It appears to be a shim for Function.bind() .

But I don't understand it and what it's doing, specifically the args.concat part. What does concat do?

Array.concat() concatenates two or more Array s (as well as other values to an Array ).

Also, what does .bind method do that .apply and .call can't?

It returns a reference to a function with this bound to whatever you desire.

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

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

It is useful for currying, eg returning a function which has arguments already set (as beyond setting this in bind() , you can set default arguments).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM