[英]Calling a prototype function via button click not working
這是為嘗試使用模型 - 視圖 - 控制器設計模式而構建的程序的一部分。 據我了解,我不能在處理click事件的函數中使用this
關鍵字本身。 但是當我使用_this
,我得到了錯誤: Uncaught TypeError: _this.saveCastle is not a function.
此外,當我在_this
上使用console.log時,它返回了全局對象,我相信它應該指向本地函數。
任何反饋都表示贊賞,謝謝。
var CreateCastleView = (function () {
function CreateCastleView(document, controller, model, validationResult) {
this.document = document;
this.controller = controller;
this.model = model;
this.validationResult = validationResult;
var _this = this;
this.document.getElementById('save').addEventListener('click', function() {
return _this.saveCastle();
});
CreateCastleView.prototype.saveCastle = function() {
console.log("This isn't being called");
};
return CreateCastleView;
})();
我無法100%確定,因為您沒有顯示對象的客戶端代碼,但是以下內容會產生所需的結果:
1 <html>
2 <head>
3 <script>
4 document.addEventListener( "DOMContentLoaded", function( event ){
5 var CreateCastleView = (function () {
6
7 function CreateCastleView(document, controller, model, validationResult) {
8 this.document = document;
9 this.controller = controller;
10 this.model = model;
11 this.validationResult = validationResult;
12
13 var _this = this;
14
15 this.document.getElementById('save').addEventListener('click', function() {
16 return _this.saveCastle();
17 });
18 }
19
20 CreateCastleView.prototype.saveCastle = function() {
21 console.log("This isn't being called");
22 };
23 return CreateCastleView;
24 })();
25 new CreateCastleView( document );
26 });
27 </script>
28 </head>
29 <body>
30 <h1 id='save'>Click me</h1>
31 </body>
32 </html>
這兩個關鍵部分位於#25和#18線上。 如果您將CreateCastleView作為函數調用(省略' new '關鍵字),那么結果就是您描述的問題。 如果不使用函數作為構造函數或方法,則使用默認的“ this ”對象,這通常是窗口全局別名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.