Javascript对象构造函数设置为undefined

时间:2016-11-14 18:02:25

标签: javascript object prototype undefined

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

我无法弄清楚为什么它会在未定义的情况下进入,因为它甚至在构建函数被调用之前被设置了。

更新:这个小提琴具有被调用的确切代码。 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 个答案:

答案 0 :(得分:6)

问题是您在定义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()