1

I'm want to use my Parent's class methods in my child class.
In classical OOP, you would simply extend your child class to make use of your parents' functionality, is this possible using prototype?

Here is my file structure:

Parent.js

var Parent = function(){
    this.add = function(num) {
        return num + 1;
    };
};

module.exports = Parent;

Child.js

var Parent = require("./parent.js"),
    util = require("util");

var Child = function() {

    this.sum = function(num) {
        // I want to be able to use Parent.add() without instantiating inside the class 
        // like this:
        console.log(add(num));
    };
};

util.inherits(Child, Parent);

module.exports = Child;

program.js

var child = require("./child.js");

var Calculator = new child();

Calculator.sum(1);

Obviously, add() is undefined here.
I've tried using util.inherits but it I'm not sure it's the right approach.

I'd also like to ask if this is a good design pattern in JavaScript in general, considering I'd like to have multiple child classes inheriting from my parent?

2
  • 1
    You have to write it as this.add(num). Commented Dec 20, 2014 at 19:13
  • And also you have to do Parent.call(this) in the Child constructor Commented Dec 20, 2014 at 19:24

1 Answer 1

1

There are two issues with your code:

First, as mentioned in the comments by @Pointy, the add method in Child.js should be qualified with this.. This is because using add will resolve it to the root scope (window in browsers).

Second, you are binding the add method in Parent to each particular instance independently, by using this.add = function(...){...}. Bind it to the Parent prototype and you'll get what you want.

var Parent = function() {}
Parent.prototype.add = function(num) { return num + 1; }

The function Parent.prototype.add will be inferred to all instances of Parent and its derived objects.

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.