Javascript Array Member Variable - Undefined with prototype

In the code below, the pushElement method works fine when working with the "words" variable, but as soon as I run the popElement method, it fails in the "this.words.length" part with the following error: "Uncaught TypeError: Unable to read the property" length " undefined ".

Any ideas?

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 

EDIT: The code above is perfect. It was in my actual implementation that I used the code above. I use setInterval to call popElement (), which changes the scope of this. Read the full answer here:

http://forrst.com/posts/Javascript_Array_Member_Variable_is_Undefined_wi-g6V

+4
source share
1 answer

@ Already found the answer, but here is the explanation.

If you call the function as follows:

 AS.popElement(); 

the popElement function is executed in the context of the AS object (the value "this" refers to AS). But if you use setInterval (or any callback function) as follows:

 setInterval(AS.popElement, 1000); 

you only pass a link to the popElement function. Therefore, when popElement is executed 1000 milliseconds later, it is executed in the global context (this means that "this" refers to the window). You will get the same error if you called:

 window.popElement(); 

A possible alternative to this is to avoid the following:

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

Another option would be to use the apply or call methods to explicitly indicate your context:

 setInterval(AS.popElement.apply(AS), 1000); 
+1
source

Source: https://habr.com/ru/post/1341463/


All Articles