[英]Passing a function as an object property
This is what I would like to do: 这是我想做的:
function genTxnId(id) {
return id;
}
var ws;
ws = new funcB('A', {evaluator: genTxnId(25)});
But I find that once it goes into funcB, the "evaluator" property of the passed in object is evaluated before going into the function. 但是我发现,一旦进入funcB,传入的对象的“ evaluator”属性将在进入函数之前进行评估。 Is there anyway to keep it as genTxnId(25) until it is used within funcB. 无论如何,在funcB中使用它之前,请将其保留为genTxnId(25)。
I know that doing this would keep it as a function: 我知道这样做会使其保持功能:
var funcA = function(b) { return b;
Would keep it as a function but then I won't be able to pass in argument b. 会将其保留为一个函数,但随后我将无法传递参数b。
Using .bind()
, you can bind the parameters of the function to specific values without calling it. 使用.bind()
,可以将函数的参数绑定到特定的值,而无需调用它。 .bind()
will return a function that you can then call elsewhere, passing in the remaining arguments that haven't been bound. .bind()
将返回一个函数,您可以在其他地方调用该函数,并传递尚未绑定的其余参数。
function getTxnId (id) {
return id;
}
function funcB (str, obj) {
obj.evaluator();
}
var ws = new funcB('A', {
evaluator: genTxnId.bind(this, 25)
});
The one caveat is that bind takes as its first parameter the object to which this
will be bound. 一个需要注意的是,结合作为它的第一个参数要将对象this
将被绑定。 This means that you can't depend on the value of this
in getTxnId
to refer to the newly created object, which may seem more intuitive (albeit impossible, to my knowledge). 这意味着您不能依靠getTxnId
的this
值来引用新创建的对象,这似乎更直观(尽管据我所知不可能)。 But in general, you won't need to do that, so you can pass in any old object. 但是通常,您不需要这样做,因此您可以传入任何旧对象。 You could even pass null
if you won't ever use this
inside that function, ie getTxnId.bind(null, 25)
. 如果您永远不会在该函数内使用this
函数,甚至可以传递null
,即getTxnId.bind(null, 25)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.