在下面的代碼中,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