I have a problem that I can't work around.
The context is: I want to have an inheritance chain, and a method of objects that belong to this inheritance has to be a event handler, and at the same time be able to reach the object properties.
I am giving a try to writing JavaScript without the "new" word, and using instead Object.create() with some inheritance hierarchy. So first this approach.
So I have a blueprint for the rest of my objects (myProto), and then I create objects with Object.create (so that there is no closure where I can do the trick of assigning this
to that
or self
). Now, when I use a method of this object to handle, for instance, a click event on a div, this
obviously will refer to the DOM object, and I lose the posibility of accessing the properties of my object.
var myProto = {
init: function (name, value) {
this.name = name;
this.value = value;
return this;
},
someHandler: function (e) {
// Normally I would use this instead of e.target...
e.target.innerHTML = this.name + this.value; // This does not refer to the object.
}
};
var myObject = Object.create(myProto).init('myName', 'myValue');
document.getElementById('myDiv').onclick = myObject.someHandler;
Here the fiddle: http://jsfiddle.net/pgPHM/
And now the "classical" approach: If I was using the new Constructor form, it would be easy to assign this in the closure and then access it, but there is the problem that the functions in the Constructor.prototype
var Constructor = function (name, value) {
var self = this;
self.name = name;
self.value = value;
};
Constructor.prototype.someHandler = function () {/*self does not reach this here*/};
jsfiddle: http://jsfiddle.net/ZcG3J/2/
I really don't get why JS objects do not have a real this
or self
or whatever to refer to themselves without these tricky contexts, closures, etc...
Basically the question is:
How can I use a method of an object as an event handler, and still be able to reach the object?