0

First of all, I want to say I really tried searching for this because I feel as if this has been asked before. Perhaps I'm using the wrong terminology, but I haven't found anything yet. Anyways the question is:

Suppose I have a parent class:

function Parent(){
    this.say = function(words){
        console.log(words);
    };
}

And a child class that inherits from this:

function Child(){
    Parent.call(this);
}

I want the child class to have the say function except I want to predefine the arguments. For example, the non-ideal way to do this would be to just rewrite the function by adding:

this.say = function(){
    console.log("hello")
}

But I would much rather somehow call the parent's say function and specify the argument "hello"

How would do you do this? OR - is this the wrong way to think about javascript inheritance and if so, what would you recommend?

1 Answer 1

2

The right thing to do would be to put methods shared by all instances on the prototype and instance specific code in the constructor.

You can override any method on the prototype of the child if you want to:

function Parent(){ }

Parent.prototype.say = function(words) {
    console.log(words);
};


function Child() {
    Parent.call(this); // apply parent constructor to instance
}

Child.prototype = Object.create(Parent.prototype); // establish inheritance
Child.prototype.constructor = Child;

Child.prototype.say = function() { // override method
     // call parent method with specific argument
     Parent.prototype.say.call(this, 'hello');
};

.call (and .apply) let you call a function and explicitly set what this should refer to inside the function. In this case we are calling the .say method of the parent constructor, but since we also pass this, it's like as if the method was called on an instance of Child.

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.