With javascript, you can have one object inherit properties from another, so that if a property is not found on the first object, the second object is searched for it. By reassigning the prototype
property on a constructor function, you can create chains of many objects to search for a property.
For example:
var X = function() {};
X.prototype.x = "x";
var Y = function() {};
Y.prototype = new X();
Y.prototype.y = "y";
var z = new Y();
z.z = "z";
///////////////
console.log(z.z); // searches z for property 'z', finds it and returns 'z'
console.log(z.y); // searches z, fails, searches z.[[hidden_prototype]]
// (which is Y.prototype), finds it and returns 'y'
console.log(z.x); // searches z, fails, searches Y.prototype, fails,
// searches Y.prototype.[[hidden_prototype]]
// (which is X.prototype), finds it and returns "x"
I was wondering though whether it was possible to extend that to properties on the constructor functions, ie X
and Y
in the above code. For example, is there a way to alter the above code so that the following will also work:
X.val = 42;
console.log(Y.val); // returns 42
This would work if Y.[[hidden_prototype]] === X
, but I have no idea how to set that when X
and Y
also have to be constructor functions.