View Full Version : Having fundamental javascript OO problems

02-07-2007, 12:07 PM

I'm new to javascript, and I'm trying to inmplement OO programming using javascript.

I have created an object called MhukWindow with various attributes, on a test page I am calling a function (downPressedScroller) on a button click, which in turn calls another function(downPressed).

within the downPressed function I try an access a object variable (currentV) which is initialised to zero. but this is coming back as undefined.

I can't fugure out why and this is driving me nuts! I need to understand such a fundamental problem if I am to learn javascript.

please help, my code is outlined below :-

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>

<script type="text/javascript">
function MhukWindow()
this.increment = 2;

this.currentV = 0;

this.scrollTimer = null;
this.currentWindow = 'abc';
//......more variables

this.downPressedScroller = function(wndw)
currentWindow = wndw;
alert('current window: ' + this.currentWindow); //ok

this.scrollTimer = setInterval(this.downPressed,2000);

this.downPressed = function()
alert('current V: ' + this.currentV); //comes back as undefined
var mhuk = new MhukWindow();

alert('created instance');

<input type="button" value="click me" onclick="mhuk.downPressedScroller('wndw');"/>

02-07-2007, 12:40 PM
this.scrollTimer = setInterval(this.downPressed,2000);

This takes the function object stored in the downPressed property of the this object and calls it in 2 seconds. This is similar to if you did this:
return (this===obj);
alert(func());// ==> falseIf you try that code, you'll see that the this object has to do with how the function is called, not with what object it was placed upon. The same function may be a member of many different objects...

To correct for this, you need to change your code a bit:

02-07-2007, 12:55 PM

I also came to the same conclusion that the this keyword was referring to the calling function. But hadn't come up with a fix yet!

Thanks for the prompt reply works a treat.