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
bindfunction takes a function and ensures that it is always bound to a specificthisvalue. The easiest example is in event handlers. By default, event handler’sthisvalue is bound towindow. However, let’s say that you want to use an object’s method as a listener, and in that listener change some properties:On the onload event, instead of
thing.answerbeing changed like intended,window.answeris now 42. So, we usebind:So,
bindreturns a function, that when called, calls the original function, but with the specifiedthisvalue.[].concatsimply 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 thebindfunction 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.