假设我们有以下示例 Javascript 代码:
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);
出于演示目的,这被简化了很多,但要点是provider1
已经绑定,而provider2
不是 - 消费者不能将自己this
作为provider1
.
问题:有没有办法检测这种函数已经绑定的情况?有没有办法provider1
将消费者用作this
?假设答案是否定的,解决这种情况的最佳方法是什么?