2

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.

David Miani
  • 14,518
  • 2
  • 47
  • 66

2 Answers2

1

According to the first related link

You can do something like :

function Y(){}
function X(){}
Y.__proto__=X;
X.val=42;
console.log(Y.val);//42

Though it is apparently not standard

Community
  • 1
  • 1
grodzi
  • 5,633
  • 1
  • 15
  • 15
  • Thanks, that is what I wanted to know, didn't see the related link when I typed the question. By the looks of it the possible answers lists is updated by the contents of not just the title, but also the text - should check it again after typing the question :) – David Miani Jul 25 '11 at 12:45
  • 2
    You should not use the non-standard, deprecated __proto__ property. It is not widely supported and will be removed from the browsers that do support it in the future. – RobG Jul 25 '11 at 13:00
0

You can use a clone function first developed by Lasse Reichstein Nielson and popularised by Douglas Crockford as "beget":

var clone = (function() {
  var f = function(){};
  return function(obj) {
    f.prototype = obj;
    return new f();
  }
}());

To set X as Y[[Prototype]]:

function X(){}
var Y = clone(X);

However Y will be an object, not a function. Functions can only be created by the Function constructor. How it creates new functions is defined in ECMA-262, you can't influence which object it uses as the [[Prototype]] object because functions must inherit from Function.prototype and Object.prototype, so it can't allow just any object to be inserted as the [[Prototype]].

RobG
  • 142,382
  • 31
  • 172
  • 209