[英]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.