3
Function.prototype.bind = function(){
  var fn = this, 
      // clone arguments
      args = Array.prototype.slice.call(arguments), 
      // get the first argument, which should be an object, and args will be modified. 
      object = args.shift();
  return function(){
    return fn.apply(object,
      // why use concat??? why? 
      args.concat(Array.prototype.slice.call(arguments)));
  };
};
...
elem.onclick = Button.click.bind(Button, false);
....

I saw above code from here: http://ejohn.org/apps/learn/#86 while learning javascript. The code is an excerpt from prototype.js. The comments are added by me, not from original code.

My question is why use args.concat(Array.prototype.slice.call(arguments)))? I think pass args is enough. The bind() in prototype.js must have its valid reason. Please help me understand it. Thank you!

1 Answer 1

4

Well, you also want to to able to access the arguments passed to the bound function, not only the arguments bound to the function.

args refers to the arguments passed to .bind and arguments refers to the arguments passed to the bound function (the one returned by .bind).

Make the changes to .bind and compare the versions with the following function:

function foo() {
    console.log(arguments);
}

var bound = foo.bind(null, 1, 2);
bound(3, 4);

With args.concat(Array.prototype.slice.call(arguments)));, the output will be

[1, 2, 3, 4]

with args only, it will be

[1, 2]

In case of the event handler, you won't be able to access the event object passed to it if you'd only use args.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Your last sentence helps me a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.