Search code examples
javascriptvisitor-pattern

Java script visitor sample is not working


I need to use logic like visitor pattern and I've created new sample which failed in visitor.visit(self); and I got error undefined is not a function, any idea what am I missing?

var Entity = function (file,name) {
    var self = this;
    var name;
    var type;
    var log = {};

    this.setName = function (name) {
        this.name = name;
    };

    this.accept = function (visitor) {
        visitor.visit(self);
    };

    this.getName = function () {
        return name;
    };


    this.getType = function () {
        return type;
    };

    this.getLog = function () {
        return log;
    };
};

//Start using visitor


var verifyFile = function () {
    this.visit = function (file) {
       alert("test");
    };
};




function test(){
  var file = new Entity();
    file.accept(verifyFile);

};

Solution

  • You are injecting a function that defines a function, but your code is looking for an object that contains a function - see below

    var Entity = function(file, name) {
      var self = this;
      var name;
      var type;
      var log = {};
    
      this.setName = function(name) {
        this.name = name;
      };
    
      this.accept = function(visitor) {
        visitor.visit(self);
      };
    
      this.getName = function() {
        return name;
      };
    
    
      this.getType = function() {
        return type;
      };
    
      this.getLog = function() {
        return log;
      };
    };
    
    //Start using visitor
    
    
    var verifyFile = {
      visit : function(file) {
        alert("test");
      }
    };
    
    
    function test() {
      var file = new Entity();
      file.accept(verifyFile);
    };
    
    test()