当我尝试调用对象方法中的JavaScript这种特别的方式,我得到以下错误:
TypeError: listener.update is not a function
我的代码:
<html>
<head>
<script src="library.js"></script>
</head>
<body>
<script>
// manages listeners etc.
function Model() {
var listeners = [];
this.addListener = function(listener) {
listeners.push(listener);
};
// the model will call the listeners when "setting the selection"
this.setSelection = function() {
for (listener in listeners)
listener.update();
};
};
// test function that will be used as update
function moveon() {
var answer = confirm("Ready to move on?");
if (answer) window.location = "http://google.com";
}
// create a model and add a listener
var model = new Model();
var listnr = {};
listnr.update = moveon;
model.addListener(listnr);
// update listener
setTimeout(model.setSelection, 2000); // this doesn't work
// setTimeout(listnr.update, 2000); // but this does
</script>
</body>
</html>
代码的说明:
Model
对象管理着一个列表listeners
,并在某些状态发生变化时调用它们的update
方法。在我的例子中,当setSelection
被调用时会发生这种情况。
注:
的错误不是很有见地,而且,如果我去掉最后一行,listnr.update
工作正常。
问:
为什么我得到这个错误时,该方法是从模型称为和/或如何解决我这个问题?
请考虑使用调试器之前去SO –
如何?用调试器还能弄清楚什么?那是什么? :p – Sebi
你可以检查你的侦听器对象,看看它是什么更新属性... –