Javascript访客示例无效

时间:2014-12-25 07:12:24

标签: javascript visitor

我需要使用像访问者模式这样的逻辑,我创建了新的 在visitor.visit(self);失败的示例,我收到错误未定义不是函数, 知道我错过了什么吗?

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);

};

1 个答案:

答案 0 :(得分:0)

您正在注入一个定义函数的函数,但您的代码正在查找包含函数的对象 - 请参阅下面的

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()