TypeError ...不是构造函数

时间:2016-09-12 23:00:25

标签: javascript jquery function object constructor

我有以下内容,它是解析器函数的开头。它依赖于jQuery扩展。我试图删除jQuery依赖,但是当我这样做时,我得到的是VastParser不是构造函数'。我想我需要重新设计如何创建基础对象以使其工作。想法?

var VASTParser = $.extend(function(){}, {
  constructor: function() {
    // only work once...
    if (VASTParser._instance) {
      this.parse = null;
      this.parseVast = null;
      throw "VASTParser is a Singlton. Access via getInstance()";
    }

    VASTParser._instance = this;
    console.log("VASTParser instantiated.", "", "VAST");
  },
  parse: function(xml) {
    console.log(xml);
  }
});

// create static getInstance()
VASTParser.getInstance = function() {
  if (!VASTParser._instance) {
    VASTParser._instance = new VASTParser();
  }
  console.log(VASTParser._instance);
  return VASTParser._instance;
};

// call it, to prevent the constructor from being succeeding via direct calls again
VASTParser.getInstance();

1 个答案:

答案 0 :(得分:0)

根据评论,不需要构造函数,因为它是一个单例对象 -

var VASTParser = { 
  parse: function(xml) { 
    console.log(xml); 
  } 
}; 

VASTParser.parse = function(xml) { 
  return xml; 
}; 

VASTParser.parse({test: 'test xml'});