这件事已经困扰我好几个小时了。我有一个文件,它定义了一个Javascript类对象,然后在定义之后立即实例化这个类。我收到了一个not defined错误,就好像类没有定义一样,而实际上它是很清楚的:
(function($) {
function NewsSlider(element, children) {
this.element = element;
this.children = children;
this.currentItem = 0;
this.maxCount = this.children.length;
}
NewsSlider.prototype.displayItem = function() {
this.children.hide();
this.children[this.currentItem].show();
}
NewsSlider.prototype.startNewSlider = function() {
if(this.currentItem > this.maxCount) {
this.currentItem = 0;
}
setTimeout(function() {
this.displayItem();
}, 5000);
}
})(jQuery);
var a = new NewsSlider();下面是我得到的错误:
ReferenceError: NewsSlider is not defined
var newsSliders = new NewsSlider("#news-ticker ul", "#news-ticker ul li");现在,我似乎在这段代码中看不到任何问题,并且以前已经做过很多次了,所以有人能告诉我哪里出了问题吗?或者我在哪里犯了傻?谢谢
发布于 2015-01-15 06:00:25
您在另一个函数中声明了NewsSlider,因此它的作用域是该函数。
你试图在它不存在的函数外部使用它。
将function NewsSlider(element, children) { ... }移出匿名函数或将var a = new NewsSlider();移入匿名函数。
由于您不使用jQuery或创建除NewsSlider之外的任何顶级作用域变量,因此您最好完全正确地使用匿名函数。
发布于 2015-01-15 06:00:36
这是一个作用域错误,是将代码放在闭包中的结果。这实际上是闭包的一个特性,也正是您应该使用它们的原因。所以你不能访问里面定义的变量。这是为了防止全局命名空间的污染。
你可以在你的闭包之外定义NewsSlider,你可以从你的闭包中返回NewsSlider并将它赋给一个新的var,或者你也可以一起消除闭包。
选项1:
var NewsSlider;
(function($) {
NewsSlider = function(element, children) {
this.element = element;
this.children = children;
this.currentItem = 0;
this.maxCount = this.children.length;
}
})(jQuery);
var a = new NewsSlider();选项2:
var NewsSlider = (function($) {
var NewsSlider = function(element, children) {
this.element = element;
this.children = children;
this.currentItem = 0;
this.maxCount = this.children.length;
}
return NewsSlider;
})(jQuery);
var a = new NewsSlider();选项3:
function NewsSlider(element, children) {
this.element = element;
this.children = children;
this.currentItem = 0;
this.maxCount = this.children.length;
}
var a = new NewsSlider();发布于 2015-01-15 06:07:00
如果它对存在的对象一无所知,就不能期望它“认为”类已经被定义了。
您已经在闭包中定义了您的类,因此一旦您离开该函数的作用域,jQuery就不再有对它的引用,因此您将得到一个引用错误。
考虑一下:
--> function()
| {
| class aClass definition here
|
| a = new aClass;
|
| // do some work with the class here.
|
--> } 上面的一切都很好,因为类可以在当前作用域内访问,但是考虑下面的第二个示例,我们尝试在包含类定义的函数的作用域之外为p赋值:
--> function()
| {
| class aClass definition here
|
| a = new aClass;
|
| // do some work with the class here.
|
--> }
var p = a.getParam();这里将抛出引用错误,因为p试图从当前作用域中找不到的变量中获取其值,因此会产生引用错误。
为了解决这个问题,最好对你的类有一些全局的引用。
https://stackoverflow.com/questions/27953215
复制相似问题