0

I am new to JavaScript and trying to get my head around inheritance when I have a constructor that takes parameters.

Suppose I have a base object called Base:

function Base(param1, param2) {
   // Constructor for Base that does something with params
}

I want another object, for example called BaseChild which inherits from Base and then another object called Child which inherits from BaseChild.

How would I go about creating the constructors for BaseChild and Child using basic JavaScript (i.e. no special plug-ins)?.


Note:

I thought you might be able create BaseChild as follows:

var BaseChild = new Base(param1, param2);

But I don't have the values for param1 or param2 in BaseChild, only in Child. I hope this makes sense!.

1

1 Answer 1

1
// define the Base Class
function Base() {
   // your awesome code here
}

// define the BaseChild class
function BaseChild() {
  // Call the parent constructor
  Base.call(this);
}

// define the Child class
function Child() {
  // Call the parent constructor
  BaseChild.call(this);
}


// inherit Base
BaseChild.prototype = new Base();

// correct the constructor pointer because it points to Base
BaseChild.prototype.constructor = BaseChild;

// inherit BaseChild
Child.prototype = new BaseChild();

// correct the constructor pointer because it points to BaseChild
Child.prototype.constructor = BaseChild;

alternative approach using Object.create

BaseChild.prototype = Object.create(Base.prototype);
Child.prototype = Object.create(BaseChild.prototype);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.