[英]“Uncaught TypeError: undefined is not a function” Error message in Javascript when calling a method in an object
[英]Not a Function TypeError when Calling Object Method in Javascript
問題:
當我嘗試以這種特殊方式在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
可以正常工作。
題:
為什么從模型中調用方法時出現此錯誤,並且/或者如何解決此問題?
model.setSelection
不保留對對象的引用。 如果不需要支持較舊的瀏覽器,則可以將其綁定到對象:
model.setSelection.bind(model)
如果您確實需要擔心較舊的瀏覽器,可以使用一個小的匿名函數:
function () { model.setSelection(); }
這兩種方法都將保留setSelection
工作所需的對象引用。
listnr.update
起作用的原因是因為該函數類型不同; 您構建了一個獨立的非對象函數,並將該對象的引用設置到該對象中,因此它可以正常工作。 但是,如果您嘗試使用模型進行操作,則將無法更新對象本身。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.