当test.testHello(helloWorld.sayHello);
运行时,它不能识别我插入了新的问候语,因为问候语是未定义的。我可以使用bind来确保它在适当的范围内运行,但我不确定为什么它不在适当的范围内运行。有人可以解释为什么会发生这种情况并向我展示更好的解为什么我的回调失去了它的范围?
解决方案:test.testHello(helloWorld.sayHello.bind(helloWorld));
var HelloWorldClass = function() {
this.greetings = [];
}
HelloWorldClass.prototype.addGreeting = function(greeting) {
this.greetings.push(greeting);
}
HelloWorldClass.prototype.sayHello = function() {
document.getElementById('output').innerHTML += this.greetings;
this.greetings.forEach(function(greeting) {
greeting.execute();
})
}
var TestClass = function() {
this.testHello = function(callback) {
alert("TestHello is working, now callback");
callback();
}
}
var main = function() {
var helloWorld = new HelloWorldClass();
var test = new TestClass();
helloWorld.addGreeting({
execute: function() {
alert("Konichiwa!");
}
});
helloWorld.sayHello();
test.testHello(helloWorld.sayHello);
}
main();
你说什么范围? – Vinz243
另一种考虑它的方式是'this'不是对建筑环境/范围的参考。它是对函数的* invoker *的引用。谁或调用'callback'?不是'helloWorld'。 'bind'给你一个调用者稳定的函数 –