I'm trying to encapsulate code in an object but I'm having problems with setTimeout and setInterval calling functions within an object.
Heres a simple example that attempts to increment a number displayed in the browser:
The inner function of the object abc is called but it appears to lose the value of this.total and sets the value to NaN.
Is this possible to do? This is a much simpler example than the one I am trying to figure out which involves similar calls to objects within objects.
Thanks
Heres a simple example that attempts to increment a number displayed in the browser:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script>
function abc() {
this.total = 0;
this.addOne = function() {
this.total++;
document.getElementById('abc').innerHTML = this.total;
}
document.getElementById('abc').innerHTML = this.total;
setTimeout(this.addOne, 1000);
//setTimeout("this.addOne()", 1000);
}
function init() {
new abc();
}
</script>
</head>
<body onload="init()">
<div id="abc"></div>
</body>
</html>
The inner function of the object abc is called but it appears to lose the value of this.total and sets the value to NaN.
Is this possible to do? This is a much simpler example than the one I am trying to figure out which involves similar calls to objects within objects.
Thanks