spiderplant0
Programmer
Hi, I having problems using 'this' in an objects method. I have simplified the problem.
I instantiate object obj1 which inturn instantiates subObj1. subObj1 is a slave to obj1. obj1 registers a handler function called method1 with subObj1 so that subObj1 can tell obj1 when it has finished.
For example: call subObj1.subMethod2() to get the sub object to do something.
subObj1 calls subMethod1 when its finished with its task, which inturn causes method1 to be called.
If I call method1 directly from obj1 'this' refers to obj1.
However when method1 gets called by the subObj1 through the event handler mechanism,
I find that 'this' has been changed to refer to subObj1.
This is a problem as now method1 has lost all connection with its object obj1.
If I define method1 within the 'Class1' function, I can get it to work if I use the 'var me = this;' trick, but if you have lots of methods within Class1() with further nesting this can get a bit hard to read.
So, can someone tell me how to deal with 'this' changing. I.e. I want 'this' to refer to obj1 within method1.
Thanks.
Code:
<html>
<body>
<script type="text/javascript">
function Class1(){
this.prop1 = "prop";
this.subObj1 = new SubClass1(); //sub-object
this.subObj1.subMethod1 = this.method1; //register handler
}
Class1.prototype.method1 = function(){
console.log(this.prop1);
}
function SubClass1(){
this.prop1 = "subObjProp";
this.subMethod1;
this.subMethod2 = function(){ this.subMethod1(); };
}
obj1 = new Class1();
obj1.method1(); //prints 'prop'
obj1.subObj1.subMethod2(); //prints 'subObjProp'
</script>
</body>
</html>