通过按钮单击调用原型功能不起作用

时间:2016-01-07 00:55:33

标签: javascript

这是为尝试使用模型 - 视图 - 控制器设计模式而构建的程序的一部分。据我了解,我不能在处理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;
})();

1 个答案:

答案 0 :(得分:1)

我无法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作为函数调用(省略&#39; &#39;关键字),则结果就是您描述的问题。如果不将该函数作为构造函数或方法调用,则默认情况下 &#39;使用了对象,它通常是 window 全局别名。