【问题标题】:Javascript object constructor setting as undefinedJavascript对象构造函数设置为未定义
【发布时间】:2016-11-14 18:02:25
【问题描述】:

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

我无法弄清楚为什么它会像在调用构建函数之前设置的那样未定义。

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

【问题讨论】:

    标签: javascript object prototype undefined


    【解决方案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);
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    --

    至于你的更新,问题是你有一个错字。你写的

    event.cardInfo()
    

    什么时候应该写

    events.cardInfo()
    

    【讨论】:

    • 我并没有这样定义它。我正在使用 $.extend(Wizard.prototype, { build: function(){} });来自 jquery 的方法。
    • @jamadri 然后显示您的确切代码。如您所见,这就是本例中的问题。如果您正在做其他事情并且这不能解决问题,我需要查看该代码。
    • 我将使用我创建的整个小部件的小提琴 URL 来修改它。也许它会揭示到底发生了什么xD
    • @jamadri 减少示例时,确保结果不会改变,并且可以观察到相同的问题。现在,您已收到问题的答案,请不要对问题进行编辑,以免使您获得的答案无效。而是提出一个新问题。
    • @jamadri 你检查我的更新了吗?答案在底部。
    猜你喜欢
    • 2013-10-16
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 2012-08-03
    • 2013-12-10
    相关资源
    最近更新 更多