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. Is there anyway to keep it as genTxnId(25) until it is used within funcB.
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.
Using .bind()
, you can bind the parameters of the function to specific values without calling it. .bind()
will return a function that you can then call elsewhere, passing in the remaining arguments that haven't been bound.
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 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). 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)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.