I would like to inherit a prototype where the prototype _data will have _data values from all prototypes in the prototype chain.
This is another matter. “Prototype inheritance” means that if the _data property is on the current object, it will not look further in the chain. Also, this seems like a problem with nested objects , although I'm not sure what you really want. However, it hardly makes sense to allow an array object to inherit from another array if you really want to concatenate it.
So, I think your getter is really beautiful.
This is a good (standard) way, how to achieve this? I mean using constructor correction, while Object.create and the parent prototype reference with the .prototype constructor
The constructor corrector is good, but actually useless (especially if you expect a standard Object.create ).
However, in this.__proto__.constructor.prototype either .__proto__ or .constructor.prototype is redundant. Since both of them are either non-standard or require constructor correction, you must use the standard Object.getPrototypeOf() function to get your object prototype.
Using the following very general solution, you can nest inheritance (A.proto, B-proto, B-instance, ...) arbitrarily deep. Everyone inheriting from A.prototype will have an add method that adds _data to the current object and a get method that traverses the prototype chain and collects all _data :
function A() { // this._data = []; // why not? } A.prototype._data = []; // not even explicitly needed A.prototype.add = function(rec) { if (! this.hasOwnProperty("_data")) // add it to _this_ object this._data = []; this._data.push(rec); } A.prototype.addToAllInstances = function(rec) { Object.getPrototypeOf(this).add(rec); } A.prototype.get = function() { var proto = Object.getPrototypeOf(this); var base = typeof proto.get == 'function' ? proto.get() : []; // maybe better: // var base = typeof proto.get == 'function' && Array.isArray(base = proto.get()) ? base : []; if (this.hasOwnProperty("_data")) return base.concat(this._data); // always get a copy else return base; } function B() { A.call(this); } B.prototype = Object.create(A.prototype, { constructor: { value: B }}); B.prototype._data = []; // not even explicitly needed
Usage example:
var a = new A(); var b = new B(); a.add('ai'); a.get(); // [ai] a.addToAllInstances('ap'); // === A.prototype.add('ap'); a.get(); // [ap, ai] new A().get(); // [ap] b.get(); // [ap] b.prototype.get(); // [ap] b.add('bi'); b.get(); // [ap, bi] a.addToAllInstances('aap'); b.addToAllInstances('bp'); b.get(); // [ap, aap, bp, bi]