It seems that I can’t use this inside of a setInerval function. Why is that? What is a elegant solution?
<html>
<script>
var something = function(tMessage){
this.message = tMessage;
};
something.prototype = {
start : function(counter){
document.getElementById('result').innerHTML += this.message + "+++<br />";
var looper = setInterval(
function(){
// This is printing "undefined"
document.getElementById('result').innerHTML += this.message + "<br />";
if(!counter--)
clearInterval(looper);
},
20
);
}
};
window.onload = function(){
var e = new something("hi");
e.start(2);
}
</script>
<body>
<div id="result"></div>
</body>
</html>
Edit
Thanks for the answers!! But can anyone explain the difference between sending an argument and setting and extra variable? Any memory issues?
The problem here is that when your function is invoked
thisrefers to the global object. To preserve the current scope, you could make a closure:Instead of handwaving and trying to explain closures (which I am still in the process of fully mastering), I will direct you to this excellent answer: https://stackoverflow.com/a/111200/1726343