I’m barely starting JavaScript and I’m wondering if there are any geniuses out there that can help me understand this line by line?
1: Function.prototype.bind = function(){
2: var fn = this,
3: args = Array.prototype.slice.call(arguments),
4: object = args.shift();
5: return function(){
6: return fn.apply(object,
7: args.concat(Array.prototype.slice.call(arguments)));
8: };
9: };
I’m just beginner, but if you can teach me, then you’re awesome. I know about prototypes, call, shift, apply a bit so you can skip the beginner parts (though I think you shouldn’t so other who are barely getting into JS may learn how).
Notice: I know that there’s a somewhat “similar code” asking a similar question here but I’m asking line by line explanation and they’re not (not duplicate) (also, you can skip line 8 & 9) 🙂
This is a partial implementation, in EcmaScript 3, of the EcmaScript 5
bindmethod which does partial application. It makesis equivalent to
but its also more convenient because you can do
instead of
Nit: The two are not entirely equivalent, because if the first call to
myObject.methoddoesthis.method = somethingElse;then the bound method would still call the original.To break it down:
Adds a method to the builtin function type.
Stores
thiswhich should be aFunctionin normal use so that it can be used inside a closure.Creates an array containing the arguments to
bind.Removes the first argument from
argsand stores it inobject. This will be used as thethisvalue forfnwhen it is applied later.returns a function that acts as a partially applied method. This function when called
calls the function to the left of
.bindpassing the first argument tobindasthis.applyis a special reflective method of functions which allows calling of a function with an array of arguments similar to*argsor**kwargsin python, or...in Java.passes as arguments to
fn, the arguments tobindfollowed by the argument to the closure.