0

I am trying to inherit the members from test1 into test2 but it does not work.

function inherit(a, b)
{
// none of these work
//a.prototype = b;
//a.prototype = b();
//a.prototype = new b();
//a.prototype = Object.create(b.prototype);
//a.prototype = Object.create(b);
//a.prototype = b.prototype;
}

function test1()
{
    this.val1 = 123;
}

function test2()
{
    this.val2 = 456;
}


var testInstance = new test2();

inherit(testInstance, test1);

console.log(testInstance.val1);

How can I make test2 inherit the members of test1?

John
  • 5,942
  • 3
  • 42
  • 79
  • `a.prototype = Object.create(b.prototype);` would have worked if you had passed `test2` instead of `testInstance`, and if you had called `inherit` before trying to instantiate the object with `new`. – Bergi Feb 03 '17 at 06:15
  • To "inherit" instance-specific, constructor-intialised properties the only way is to do `test1.call(this)` inside `test2`. – Bergi Feb 03 '17 at 06:16
  • @Bergi, that call this made it work per instance rather than having it share all the same members. Thanks. – John Feb 03 '17 at 06:59
  • What do you want? If you want a property to be shared, you can add it to the prototype. – Yichong Feb 03 '17 at 07:21
  • @John Yes, that is what it would be supposed to do. If you wanted to put it on the prototype to share the value amongst all instances, write `test1.prototype.val1 = 123` instead of creating it in the constructor. – Bergi Feb 03 '17 at 16:02

0 Answers0