jam*_*dri 0 javascript prototype object 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);
Run Code Online (Sandbox Code Playgroud)
问题是你的定义后缺少分号build.没有分号,你基本上是这样做的:
Wizard.prototype.build = function() {
// do stuff
}(function($, undefined) { ... })();
Run Code Online (Sandbox Code Playgroud)
意思是,你试图立即调用函数并将函数作为参数传递给它.这是你的代码在正确的地方用分号.
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);Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
-
至于你的更新,问题是你有一个错字.你写了
event.cardInfo()
Run Code Online (Sandbox Code Playgroud)
什么时候你应该写的
events.cardInfo()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
309 次 |
| 最近记录: |