Sorry this is quite long and complicated - only for the real experts - but quite fun I think.
I think it's easier to explain stuff with code - so here's a non-working example:
--------------------------
-----
function lib() {
this.parent = <the Object instance>
}
Object.prototype.lib = new lib();
var objectInstance = new Object();
objectInstance.hello = "hello world!";
alert(objectInstance.lib.p
arent.hell
o);
--------------------------
-----
This doesn't work, obviously. But I hope it illustrates what I'm trying to do - access the parent object (Object) from within the child object (lib).
I came up with this solution, which overloads Object's constructor to initialise the lib object with the reference to the parent object stored:
--------------------------
----------
---
var lib = function(parentObj) {
this.parent = parentObj;
}
var oldConstructor = Object;
Object = function() {
this.lib = new lib(this);
oldConstructor();
}
var objectInstance = new Object();
objectInstance.hello = "hello world!";
alert(objectInstance.lib.p
arent.hell
o);
--------------------------
----------
---
Success! alert displays "hello world!". BUT, the reason I wanted to do this was so that lib.parent would be available in all objects, and this isn't the case because the constructor doesn't seem to be inherited through prototype:
--------------------------
------
var lib = function(parentObj) {
this.parent = parentObj;
}
var oldConstructor = Object;
Object = function() {
this.lib = new lib(this);
oldConstructor();
}
var anObject = function() {}
anObject.prototype = new Object;
/*Object.prototype.lib = {parent: this}*/
var objectInstance = new anObject();
objectInstance.hello = "hello world!";
alert(objectInstance.lib.p
arent.hell
o);
--------------------------
------
Alert now displays "undefined" again. And it would be the same if objectInstance contained a HTMLElement or an Array object. Object's constructor is being called, but as the constructor only adds "lib" to the Object itself and not the Object's 'prototype', it doesn't get inherited by anObject. I can't add it to the Object's prototype, because this doesn't get created until after Object has been initialised.
I can't work out a solution to this, apart from putting "this.lib = new lib(this)" in the constructor of every type of object, which is obviously infeasible.
Can anyone think of a solution?
Thanks, Robin.
Start Free Trial