[英]Calling a prototype function via button click not working
This is part of a program that was built in attempt to use the Model-View-Controller design pattern. 这是为尝试使用模型 - 视图 - 控制器设计模式而构建的程序的一部分。 As I understand it, I cannot use the
this
keyword itself in the function handling a click event. 据我了解,我不能在处理click事件的函数中使用
this
关键字本身。 But when I use _this
instead, I got the error : Uncaught TypeError: _this.saveCastle is not a function.
但是当我使用
_this
,我得到了错误: Uncaught TypeError: _this.saveCastle is not a function.
Also, when I used console.log on _this
, it returned the global object and I had believed it should point to the local function. 此外,当我在
_this
上使用console.log时,它返回了全局对象,我相信它应该指向本地函数。
Any feedback is appreciated, thanks. 任何反馈都表示赞赏,谢谢。
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;
})();
I can't be 100% sure because you aren't showing your client code of the object, however the following produces the desired results: 我无法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>
The two key pieces being on line #25 and #18. 这两个关键部分位于#25和#18线上。 If you invoke the CreateCastleView as a function (omitting the ' new ' keyword) then the result is your described problem.
如果您将CreateCastleView作为函数调用(省略' new '关键字),那么结果就是您描述的问题。 Without invoking the function as a constructor or method the default ' this ' object is used, which is usually aliasing the window global.
如果不使用函数作为构造函数或方法,则使用默认的“ this ”对象,这通常是窗口全局别名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.