Javascript class help.

Associate
Joined
26 Jun 2003
Posts
1,140
Location
North West
Im creating a class to carry out certain functionalities.

Here is a snipet of the code where I am having the problem.

Code:
function MyClass()
{

  this.AddItem = function(id)
  {
     var theItem = document.getElementById(id);

     theItem.onmouseclick = function()
     {
       this.doThis(); // <------ PROBLEM
     }

  };

  this.doThis = function()
  {
    alert("Done it");
  };

}

the "this.doThis()" needs to call the class function 'doThis' but at the moment it is thinking the 'doThis' method exists in the object 'theItem', but I dont know how to call the function 'doThis' properly.

Can anyone give me a hand?

Thanks a lot.
 
Hi,

I ran into this problem too, it was due to the meaning of "this" changing. What I did was to set a variable at the start of my JavaScript that pointed to this. e.g

var me = this;

When a function is called this invokes a further function passing in "me" as an argument. That way "me" will always be pointing at what you regard as "this".

I've got some sample code I can dig out if that would help.

Jim
 
Back
Top Bottom