在下面的代码中,pushElement方法在处理“words”变量时工作得很好,但是一旦我运行popElement方法,就会失败“this.words .length“块,出现以下错误:”Uncaught TypeError:无法读取未定义的属性“长度”。JavaScript数组成员变量未定义,使用原型方法
任何想法?
function AnimationStack() {
this.words = [];
}
AnimationStack.prototype.pushElement = function(element) {
this.words.push(element);
}
AnimationStack.prototype.popElement = function() {
if (this.words.length>0) {
var element = this.words.shift();
return element;
} else {
return null;
}
}
var AS = new AnimationStack();
var element = $("<div></div>");
AS.pushElement(element); // works perfect
AS.pushElement(element); // works perfect
AS.pushElement(element); // works perfect
var pop = AS.popElement(); // always fails
编辑:上面的代码是完美的。这是我实际执行上述代码的方式。我使用setInterval来调用popElement(),它改变了“this”的范围。阅读完整的答案:
http://forrst.com/posts/Javascript_Array_Member_Variable_is_Undefined_wi-g6V
此代码适用于我:http://jsfiddle.net/aRv99/ – Douglas 2011-02-26 19:40:14
也适合我。 – johusman 2011-02-26 19:41:52
dang,感谢repsonses ...它为Chrome浏览器和Firefox提供帮助。 jsfiddle.net真的很酷btw。 – 2011-02-26 19:43:04