The problem is that you need a link to your object. The children of an object don't know who their parents are, because they can be hosted by any parent or by no parent at all:
var myobject1={ func1:function(){alert(1);} }
var myobject2={ func2: myobject1.func1 }
var func3 = myobject1.func1;
It is the exact same anonymous function that is assigned to myobject1.func1, myobject2.func2 and to the variable func3. There is no way that it can know what object it hosted by, since it, as you can see, can be hosted by several objects at once.
The normal way to solve that problem is to use a closure in the objects constructor. If you don't want to use that you have to give the link to the object in some other way.
If you want to assign the event handler in html, you can use this:
<button onclick="myobject.handle_click.call(myobject,this);"/>
When the handle_click is called, "this" will refer to myobject, and your first parameter will be a link to the object that fired the event. Note that you have to enter the name of the object as the first parameter to "call".
If you want to assign it in javscript you have to give the link in another way. If you have this object:
var myobject = {
y:1;
handle_click:function() {
var myself = arguments.callee.myself; // Get the link to the object
alert(myself.y);
}
}
Assign a link to the object and set the onlick event on your element:
myobject.handle_click.myself = myobject; // set the link
element.onclick = myobject.handle_click;
With the technique above the function always have a link to the object that you have specified. Even if you assign it to a variable or another object, it still have the handle to your first object.
With your example you can use this:
var myobject = {
y : 1,
handle_click : function (e) {
var myself = arguments.callee.myself;
alert('handling click ' + myself.y);
return false;
},
load : function () {
this.handle_click.myself = this;
document.getElementById('x').onclick = this.handle_click;
}
};
myobject.load();
The main drawback with the method above is that you have to assign the link to every function that needs it.
var myobject = new function () {
var myself = this;
myself.y = 2;
myself.handle_click=function(e) {
alert('handling click ' + myself.y);
return false;
};
myself.load = function () {
document.getElementById('btn2').onclick = myself.handle_click;
}
}();
With the closure above, every function has access to itself, regardless of how it was called.