當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'給你一個調用者穩定的函數 –