看來我不能在setInerval
函數裏面使用this
。這是爲什麼?什麼是優雅的解決方案?在setInterval裏面不能使用'this'
<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>
編輯
感謝您的答案!但任何人都可以解釋發送參數和設置和額外變量之間的區別嗎?任何內存問題?
因爲這個==窗口裏面的setInterval()回調函數 –