Bind more arguments of an already bound function in Javascript

江枫思渺然 提交于 2019-11-26 20:45:43

Once you bound an object to a function with bind, you cannot override it. It's clearly written in the specs, as you can see in MDN documentation:

"The bind() function creates a new function (a bound function) with the same function body (internal call property in ECMAScript 5 terms) as the function it is being called on (the bound function's target function) with the this value bound to the first argument of bind(), which cannot be overridden."

That means, also if you do:

g.call(1);

You will get obj as this, and not 1 – on the browsers that follows the specs.

You can of course binds multiple arguments, so:

var sum = function(a, b, c) { return a + b + c };
var sumAB = sum.bind(null, 1, 5);
var sumC = sumAB.bind(null, 2);

console.log(sumC());

But the context object will be always the one specified with the first bind, because it cannot be overwritten.

Just to avoid confusion, the first argument of call is the context object (this), then you will have the rest of the argument.

It means:

var obj = { foo: function(bar) { console.log(bar) } };

obj.foo('hello');

// equivalent to:
var foo = obj.foo;

foo.call(obj, 'hello');

Hope it helps.

You never passed any arguments — you only ever set context. call's first argument is received as context (this), and arguments 2 onwards are received as the called function's arguments 1 and onwards. Meanwhile, bind creates a new function with a new context — arguments are passed when it's invoked.

Here are ways of passing 1 as function f's argument a following on from your first code block:

f( 1 );
g( 1 );
g.call( this, 1 );
g.apply( this, [ 1 ] );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!