简体   繁体   中英

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. But when I use _this instead, I got the error : 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.

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:

  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. If you invoke the CreateCastleView as a function (omitting the ' new ' keyword) then the result is your described problem. Without invoking the function as a constructor or method the default ' this ' object is used, which is usually aliasing the window global.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM