Please take a look at https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
If I were to code the bind functionality myself, it would look something like this:
Function.prototype.bind = function(thisArg, ...args) {
// bind is a function on the Function's prototype, therefore it will be
// in the 'this' variable of this function. For further reference see link 1. below.
var originalFunc = this;
// A new function is returned wrapping the original function. When this new function is
// called it will call the original function with the thisArg and other args passed
// to the bind function and appends the args passed to this new function after
// the arguments passed to `bind`.
return function(...secondaryArgs) {
return originalFunc.call(thisArg, ...args, ...secondaryArgs);
}
}
Note: This isn't entirely according to the spec, but it should give you an overal idea on how this would work.
As you can see calling the function returned by bind
with another set of arguments (which is what you are supposedly are trying to do) does not replace the arguments passed to bind
, but instead appends them at the very end.
This is why your example does not work as expected:
function foo(a, b) {
console.log(a, b);
}
var newFunc = foo.bind({}, 200, 300);
foo(400, 500); // prints: 200, 300 instead of what you expected: 400, 500
Changing your example a bit to understand what is going on:
function bar(a, b, c, d) {
console.log(a, b, c, d);
}
var newFunc = bar.bind({}, 200, 300);
newFunc(400, 500); // prints: 200, 300, 400, 500
Note the 400, 500 are appended after the 200, 300.
The following would also work:
var newFunc = foo.bind({});
foo(400, 500); // prints: 400, 500
Links
- How does the "this" keyword work?
Edit:
- Apparently
bind
appends the arguments instead of ignoring them.