L
Lasse Reichstein Nielsen
VK said:// It would be nice to get a reference to C2
// by using:
alert(obj1.constructor.constructor);
// but it returns native Function constructor
That could be due to my ignorance (and it most probably is) but "the
end of chain" comes too quickly. I would prefer to have constructors
inheritance tree but itself and do not bother with it manually.
"Constructor functions" in Javascript are not part of the inheritance
chain at all. In your example, you have no inheritance at all, except
what is created by the "new C1()" expression.
....
There are a lot of things one can do with JavaScript ;-)
But what would be the purpose of the above? And how does it facilitate
the inheritance management?
The clone function takes an object as parameter, and then creates a
new object with the given object as its prototype. That means that
var o = {};
var p = clone(o);
o.foo = 42;
alert(p.foo); //alerts 42, because "p" inherits all properties from "o".
Try this usage of "clone" for inheritance:
function LC2() {
this.foo = 42;
}
LC2.prototype.getFoo = function getFoo() { return this.foo; };
function LC1() {
LC2.call(this);
this.bar = 37;
}
LC1.prototype = clone(LC2.prototype);
LC1.prototype.constructor = LC1;
LC1.prototype.getBar = function getBar() { return this.bar; };
var l1 = new LC1();
alert(l1.getFoo());
LC2.prototype.getBaz = function getBaz() { return "voodoo"; }
alert(l1.getBaz());
Here you see actual inheritance between objects. The created object
referred to by "l1" has both LC1.prototype and LC2.prototype in its
prototype inheritance path.
The constructor functions themselves are forgotten as soon as the
objects are created. They merely initalize the object. You can
visualize it as:
LC2 -------- .prototype ------> { getFoo: ... }
^ ^
|(calls) | [Proto]
LC1 -------- .prototype ------> { getBar: ... }
^
| [Proto]
l1
The inheritance happens between the objects only. Functions are merely
mediators for creating the new objects and giving them a prototype
chain. The default chain of a new object, if you don't change the
prototype object of a constructor function, is just the function's
prototype object followed by (the initial value of) Object.prototype.
/L