[英]Getting a error “Uncaught TypeError: undefined is not a function” when calling a function
[英]“Uncaught TypeError: undefined is not a function” Error message in Javascript when calling a method in an object
從HTML中的按鈕調用函數時出現問題:“未捕獲的TypeError:未定義不是函數”錯誤。 我認為這里沒有任何問題。或者有些我沒有考慮到。 在此先感謝您的答復!
我有很多JS文件,這是因為這是學校的作業,我們現在正在學習模型,視圖,控制器(MVC)方法。
我有這個按鈕:
<button onClick="ControllerBKE.reageerOpKlik()">Ok!</button>
然后,我得到了創建^“ ControllerBKE”對象的Javascript代碼:
"use strict"
window.onload = reageerOpStart();
function reageerOpStart()
{
var controllerBKE = new ControllerBKE();
}
這是應該但不響應按鈕的“ ControllerBKE”中的代碼行:
function ControllerBKE(){
this.reageerOpKlik = reageerOpKlik;
function reageerOpKlik(){
alert('hoi');
}
}
這只是大代碼的一小部分。 但是,當我單擊按鈕而不是收到“ hoi”警報時,會收到錯誤消息。
reageerOpKlik
是一個實例方法。 您必須從實例中使用它。 最簡單的解決方案(不是最好的解決方案)是創建一個全局控制器實例。 有很多方法可以消除該全局變量,但這超出了問題的范圍。
function reageerOpStart()
{
window.controllerBKE = new ControllerBKE();
}
<button onClick="window.controllerBKE.reageerOpKlik()">Ok!</button>
問題是您的代碼
<button onClick="ControllerBKE.reageerOpKlik()">Ok!</button>
正在嘗試在原型對象ControllerBKE
上調用reageerOpKlik
。
你可能的意思是
<button onClick="controllerBKE.reageerOpKlik()">Ok!</button>
其中controllerBKE
是原型的實例。
但是,您還有另一個問題。 功能:
function reageerOpStart()
{
var controllerBKE = new ControllerBKE();
}
在reageerOpStart
函數的范圍內創建controllerBKE
,這意味着它在全局范圍內不可用,這是您的按鈕單擊處理程序所期望的。
您可能要考慮:
<button onClick="APP.controllerBKE.reageerOpKlik()">Ok!</button>
APP = {}
function reageerOpStart()
{
APP.controllerBKE = new ControllerBKE();
}
或者,更好的是:
<button id="myButton">Ok!</button>
function reageerOpStart()
{
var controllerBKE = new ControllerBKE();
document.getElementById("myButton").addEventListener("click", function() {
controllerBKE.reageerOpKlik();
});
}
您所擁有的被稱為閉包 。 您的功能范圍有限。 也就是說,只能在定義它的ControllerBKE()
內部調用,而不能從函數外部調用。
不過,您實際上所做的是通過ControllerBKE
實例的屬性公開該關閉。 盡管這可行,但它更適合JavaScript的原型結構,以將其添加到ControllerBKE.prototype
。
重要的是要記住,JavaScript不是原型,也不是面向對象的 。 盡管這可能類似於面向對象的封裝,但是兩者具有不同的概念和用途。
看下面的例子:
HTML:
<button onclick="controllerBKE.reageerOpKlik()">Ok!</button>
JavaScript:
"use strict";
window.controllerBKE = new ControllerBKE();
function ControllerBKE () { }
ControllerBKE.prototype.reageerOpKlik = function () {
alert('hoi');
}
我簡化了一些代碼,並對其進行了重構,以支持JavaScript為我們提供的原型對象。
第一行是將controllerBKE變量添加到窗口對象。 這使它在頁面上具有全局作用域,從而允許您的onclick
函數對其進行訪問。
下一行是一個簡單的函數包裝器。 這將創建類型為object
的ControllerBKE
的實例。
您嘗試調用的函數現在已附加到ControllerBKE
的原型中。 這意味着使用new
關鍵字創建的ControllerBKE
任何實例都可以訪問此功能。
在下面的小提琴中查看全部功能:
參考文獻:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.