2011-02-26 67 views
4

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

+2

此代码适用于我:http://jsfiddle.net/aRv99/ – Douglas 2011-02-26 19:40:14

+0

也适合我。 – johusman 2011-02-26 19:41:52

+0

dang,感谢repsonses ...它为Chrome浏览器和Firefox提供帮助。 jsfiddle.net真的很酷btw。 – 2011-02-26 19:43:04

回答

1

@Chad已经找到了答案,但这里是解释。

如果你调用该函数是这样的:

AS.popElement(); 

的popElement功能的AS对象(意为“这”指的是AS)上下文中运行。但是如果你使用的setInterval(或任何回调风格的功能)是这样的:

setInterval(AS.popElement, 1000); 

你只传递给popElement函数的引用。所以当popElement在1000毫秒后执行时,它会在全局上下文中执行(意思是“this”是指窗口)。你会得到,如果你叫了同样的错误:

window.popElement(); 

可行的替代方案,以避免这是做到以下几点:

setInterval(function() { return AS.popElement() }, 1000); 

另一个选择可能是使用应用或调用方法来设置上下文明确:

setInterval(AS.popElement.apply(AS), 1000);