0

I'm doing a project that, optimally, needs to have a deep prototype chain. However, I've hit a wall due to how the prototype inheritance works, and nothing I tried so far could get me past it.

I'll illustrate my problem through a dummy code:

Dummy Code:

var A = function() {};

A.prototype.letter = 'a';
A.prototype.object = { super: 'a+' };

var B = function() {
  A.call( this );
};

B.prototype = Object.create( A.prototype );
B.prototype.constructor = B;

B.prototype.letter = 'b';
B.prototype.object.sub = 'b+';

var C = function() {
  A.call( this );
};

C.prototype = Object.create( A.prototype );
C.prototype.constructor = C;

C.prototype.letter = 'c';
C.prototype.object.sub = 'c+';

var a = new A();
var b = new B();
var c = new C();

What I want:

a.letter -> 'a'
b.letter -> 'b'
c.letter -> 'c'

a.object -> { super: "a+" }
b.object -> { super: "a+", sub: "b+" }
c.object -> { super: "a+", sub: "c+" }

What I get:

a.letter -> 'a' (Fine)
b.letter -> 'b' (Fine)
c.letter -> 'c' (Fine)

a.object -> { super: "a+", sub: "c+" } (Not fine)
b.object -> { super: "a+", sub: "c+" } (Not fine)  
c.object -> { super: "a+", sub: "c+" } (Fine)

So, in short, I want to let B and C modify or extend properties from objects in A prototype, but without editing whatever is in A prototype itself, so that only instances from B and C get their own respective changes. What is the best way to achieve that?

Perrow
  • 1
  • "*optimally, needs to have a deep prototype chain*" - why? – Bergi Jan 03 '21 at 07:02
  • @Bergi To avoid large chunks of repeated code. – Perrow Jan 03 '21 at 07:05
  • I would recommend to avoid putting object properties on a prototype in general - since they are shared by everything, use a static property instead. You might be looking for `B.prototype.object = Object.assign(Object.create(A.prototype.object), {sub = 'b+'});` but I'm not really sure what you need this for. – Bergi Jan 03 '21 at 07:07
  • You absolutely do not need inheritance to avoid repeating code. Just write a function and call it on multiple targets. – Bergi Jan 03 '21 at 07:08

0 Answers0