Search code examples
javascriptthis

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?


Solution

  • 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.