[英]Javascript object constructor setting as 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);
問題是您在為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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.