在Javascript中绑定更多已绑定函数的参数 [英] Bind more arguments of an already bound function in Javascript
问题描述
我尝试对javascript的bind()如何工作进行排序。
I try to sort my thoughts about how javascript's bind() works.
如果我这样做,我会看到
I see that if I do
var f = function (a) { ... }
var g = f.bind(obj);
g(1)
然后用 obj调用f
as 此
和 1
as a
。
then f is called with obj
as this
and 1
as a
.
我认为g是围绕f的包装函数。
What I thought is g is a wrapper function around f.
但当我这样做时
var f = function (a) { ... }
var g = f.bind(obj);
g.call(1)
然后用调用f 1
as this
和 a
undefined。
then f is called with 1
as this
and a
undefined.
所以看起来g不仅仅是一个简单的包装器,而且调用
以某种方式区分普通函数和绑定函数。
So it seems g is not just a simple wrapper, but call
somehow differentiates between normal and bound functions.
还有一件事是我无法多次部分应用函数。
One more thing is I cannot partially apply a function more times.
var f = function (a) { ... }
var g = f.bind(obj);
var h = g.bind(1);
h();
然后用 obj
调用f作为此
和 a
未定义。
Then f is called with obj
as this
and a
undefined.
原因是什么这种行为?
编辑
此问题中的结构实际上是错误的,看到他们看起来应该接受的答案(一般我没有注意到调用
和 bind
总是这样做需要将context参数作为第一个参数)。
The constructs in this question are actually wrong, see the accepted answer on what they should look like (in general I haven't noticed that call
and bind
do always need the context argument as the first argument).
推荐答案
将对象绑定到具有的函数时绑定
,你无法覆盖它。它清楚地写在规范中,您可以在 MDN文档中看到:
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:
bind()函数创建一个具有相同函数体的新函数(绑定函数)(ECMAScript 5术语中的内部调用属性)作为被调用的函数(绑定函数的目标函数),该值绑定到bind()的第一个参数,无法覆盖。
这意味着,如果你这样做:
That means, also if you do:
g.call(1);
您将获得 obj
此
,而不是 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());
但是上下文对象将始终是第一个 bind <指定的对象/ code>,因为它无法被覆盖。
But the context object will be always the one specified with the first bind
, because it cannot be overwritten.
为了避免混淆, call 是上下文对象( this
),那么你将拥有其余的参数。
Just to avoid confusion, the first argument of call is the context object (this
), then you will have the rest of the argument.
这意味着:
var obj = { foo: function(bar) { console.log(bar) } };
obj.foo('hello');
// equivalent to:
var foo = obj.foo;
foo.call(obj, 'hello');
希望有所帮助。
这篇关于在Javascript中绑定更多已绑定函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!