Reputation: 127
I'm pretty new to JS and it seems everything seems to have so many ways to do that will make you confused.Anyways this is what I am trying to do:
//SuperClass
function Animal(name, origin, type) {
this.name = name;
this.origin = origin;
this.type = type;
//Some function that does something
this.makeSound = function() {
return "foo";
}
}
function Mamal(name, origin, type, weight, height) {
Animal.call(this, name, origin, type);
this.weight = weight;
this.height = height;
this.makeSound = function() {
return "I am a Mamal";
}
}
So the question is how would I add a function to the Animal class AFTER it has been declared so that the Mamal class (or whatever subclass) also inherits it and can use it.
Upvotes: 0
Views: 725
Reputation: 1566
If I understand your question correctly, what you actually want to achieve is that the Mamal
class inherits methods from the Animal
class? As in your question you have referred to them as Classes, I have provided an example with classes, rather than functions.
If so, you can declare Mamal like so:
class Mamal extends Animal {
constructor(weight, height) {
super();
this.weight = weight;
this.height = height;
}
// if you want to execute the Animal implementation of makeSound
makeSound() {
return super.makeSound();
}
// if you want to overwrite the Animal implementation of makeSound
makeSound() {
return "I am a mammal";
}
}
The extends keyword is used in class declarations or class expressions to create a class as a child of another class.
Sub classing with extends Super class calls with super
Update
Find the prototypal inheritance alternative here:
function Animal(name, origin, type) {
this.name = name;
this.origin = origin;
this.type = type;
}
Animal.prototype.makeSound = function () {
return "foo";
};
function Mammal(weight, height) {
this.weight = weight;
this.height = height;
Animal.call(this); // call super constructor.
}
Mammal.prototype = Object.create(Animal.prototype); //inherit the Animal object through the prototype chain
Mammal.prototype.makeSound = function () {
return "I am a mammal";
}; //Overwrite the makeSound method inherited from Animal
const cheetah = new Animal('cheetah', 'Africa', 'mammal');
cheetah.makeSound();
//foo
const mammal = new Mammal('100kg', '1m');
mammal.makeSound();
//I am a mammal
Upvotes: 1