开发者问题收集

Javascript 对象构造函数设置为未定义

2016-11-14
960

我创建了一个新对象,并且在该对象中我有几个对象变量,但是事件(可选)对象未正确设置。当通过事件选项卡在构建函数中调用它时,它显示为未定义,我猜想这可能与异步有关。下面是我的对象和调用,以及我在引用该对象时得到的内容。

我无法弄清楚它为什么会显示为未定义,因为它甚至在调用构建函数之前就被设置了。

更新:此 fiddle 具有被调用的确切代码。 https://jsfiddle.net/trickell/Leg1gqkz/2/

问题出在 checkEvents() 方法中。

var Wizard = function(id, events) {
  this.activeTab  = '';
  this.prevTab    = '';
  this.nextTab    = '';
  this.events     = (events) ? events : {}; // Optional events object. User may define events based on tab. (ex. "tabName" : function(){})

  console.log(this.events);  // Returns object with no keys

  this.build(id);
  return this;
}

Wizard.prototype.build = function(id){
  var tab = id,
      events = this.events;

  // **** This is what's showing up as undefined!!! *****/
  console.log(events.cardInfo);  
}

(function($, undefined){

  var wiz  = new Wizard($('#package_wizard'),
    {
        cardInfo : function() {
            alert('hello world');
        }
    });

 })(jQuery);
1个回答

问题是您在 build 的定义后缺少一个分号。没有分号,您实际上是在这样做:

Wizard.prototype.build = function() {
  // do stuff
}(function($, undefined) { ... })();

这意味着,您试图 立即 调用该函数并将函数作为参数传递给它。这是您的代码,分号在正确的位置。

var Wizard = function(id, events) {
  console.log(events);
  this.activeTab = '';
  this.prevTab = '';
  this.nextTab = '';
  this.events = (events) ? events : {}; // Optional events object. User may define events based on tab. (ex. "tabName" : function(){})

  console.log(this.events); // Returns object with no keys

  this.build(id);
  return this;
}; // <-- Here's a semicolon

Wizard.prototype.build = function(id) {
  var tab = id,
    events = this.events;

  // **** This is what's showing up as undefined!!! *****/
  console.log(events.cardInfo);
}; // <-- and the original problem

(function($, undefined) {

  var wiz = new Wizard($('#package_wizard'), {
    cardInfo: function() {
      alert('hello world');
    }
  });

})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

--

至于您的更新,问题是您有拼写错误。您写的是

event.cardInfo()

而您应该写的是

events.cardInfo()
Mike Cluck
2016-11-14