2

The issue I am addressing is passing a parameter to the constructor of an object subclass.

This code -- where the function takes no parameters -- works. It includes two scenarios, one creating an instance of MyClass, the other creating an instance of MySubClass:

<input type="button" value="Scenario 1" onclick="Scenario1()" />
<input type="button" value="Scenario 2" onclick="Scenario2()" />


function MyClass() {
    this.value = "test";
}
MyClass.prototype.function = function(){
    alert(this.value);
}


function MySubClass() {
}
MySubClass.prototype = new MyClass();

function Scenario1() {
    var myClass = new MyClass();
    myClass.function();
}
function Scenario2() {
    var mySubClass = new MySubClass();
    mySubClass.function();
}

Clicking either button results in an alert box displaying "test".

Now, what I want to do is have function MyClass take a parameter. This works fine for the instance that creates MyClass directly. But the instance of MySubClass doesn't work. This is conceptually what I want:

function MyClass(val) {
    this.value = val;
}
MyClass.prototype.function = function(){
    alert(this.value);
}


function MySubClass(val) {
}
MySubClass.prototype = new MyClass();

function Scenario1() {
    var myClass = new MyClass("scenario 1");
    myClass.function();
}
function Scenario2() {
    var mySubClass = new MySubClass("scenario 2");
    mySubClass.function();
}

Scenario 1 displays "scenario 1" as expected. With Scenario 2, the "value" member is never set. Obviously from my syntax this would be the case.

Is there a syntax that achieves what I am after? Note that a constraint to any solution is that "function" must be added to the MyClass prototype, as opposed to being defined as an internal function (e.g. this.function=function())

Len White
  • 892
  • 13
  • 25

1 Answers1

1

This is how you can achieve inheritance. The way to pass values up the prototype chain is to invoke the parent constructor functions and propagate the arguments.

function Parent(x) {
  this.x = x;
}

Parent.prototype.showX = function() {
  console.log(this.x);
}

function Child(x) {
  Parent.call(this, x);  // call the parent constructor
}

Child.prototype = Object.create(Parent.prototype);

new Child('example').showX()
nem035
  • 34,790
  • 6
  • 87
  • 99