Say we have the following sample Javascript code:
var modeller = "foo";
var provider1 = function (modeller, content, optionalArg) {
alert("this: " + this + ", content: " + content + ", optionalArg: " + optionalArg);
}.bind(null, modeller);
var provider2 = function (content, optionalArg) {
alert("this: " + this + ", content: " + content + ", optionalArg: " + optionalArg);
};
var createConsumer = function () {
// some arbitrary private vars
var content = 1;
var option = 2;
var doConsume = function(provider) {
provider.apply(this, [content, option])
};
return {consume: doConsume};
};
// Now use them
var consumer = createConsumer();
consumer.consume(provider1);
consumer.consume(provider2);
This is simplified a lot for demo purposes, but the gist is that provider1 is already bound, and provider2 is not – the consumer cannot pass itself as the this argument for provider1.
The questions: Is there a way to detect this kind of case where a function is already bound? Is there a way to get provider1 to use the consumer as this? Assuming the answer is no, what is the best way to work around this sort of situation?
No.
No.
Since it seems like you want to bind an argument but not the
thisvalue, I would make an argument binder method onFunction.prototypethat returns a function with only the arguments bound, and notthis.Then you’d use it like this:
Now the
provider1function will be invoked with whatever normalthisvalue is given, but themodellerwill be bound as the first argument.