[Javascript] Please help: problem with Javascript 'this' keyword in nested objects!

Amanda Birmingham lists at imladris.com
Fri Apr 26 11:17:21 CDT 2002


Hello, List,
I apologize to anyone who has seen this question on the wdvltalk list, but 
I'm desperate for an answer in short order ...

I am having a serious *issue* with the @#$%& 'this' keyword.  Basically, I 
have a setup like this: I have two types of objects defined.  Object1 has a 
constructor that defines some methods for Object1, and these methods use 
the 'this' keyword to refer to properties of Object1.  Object2 has a 
constructor that creates a new instance of Object1 as one of its 
properties.  The Object2 then attempts to use one of the methods of its new 
Object1 property by calling "this.Object1.methodName".

Which flunks.  It flunks because methodName uses the "this" keyword inside 
it, and expects "this" to refer to an object of type 
Object1.  Unfortunately, for reasons I totally cannot fathom, when I call 
methodName as described above, the "this" it is using is the "this" for 
Object2 (the outside one).  Of course, Object2 doesn't have a bunch of 
properties that Object1 does, so methodName flunks.

Why the heck is this happening?! (I have verified that it actually 
*is*).  How do I write my methods to access the properties of their 
immediate "parent", rather than the properties of the object that 
ultimately invoked them?? (short of using "this.Object1" in place of "this" 
in methodName, which is not an option because it makes Object1 completely 
un-reusable.)

I hope I've managed to describe the issue in a way that is at least 
somewhat clear--if not, please let me know and I can send pseudocode.  Any 
suggestions would be REALLY welcome, as this problem is keeping me from 
getting anything done until I know how to get around it!

Thanks as always,

Amanda Birmingham
Web Application Developer 




More information about the Javascript mailing list