I am new to oop in Javascript and just need to get to grips with this.
If I have a class with properties
function myClass(){
this.foo=null;
}
I then use inheritance to create a child class
myChild.prototype = new myClass();
function myChild(){
alert(this.foo);
}
How do I set the property of foo when instantiating the child class e.g I want to alert ‘bar’. I don’t want to simply pass ‘bar’ to myChild as I have a list of properties to set that are relevant to a method in myClass and not myChild.
var newChild = new myChild();
You can actually find the answer to this question also in my answer to previous question and it is similar to inheritance in other languages.
If you extend a class, the constructor function of the child class has to accept its own arguments and the one for the parent class. So assuming you have:
(the implementation of
inheritscan be found in this answer).Inside
Childyou have to call the construtor of the parent class and pass the parameters, similar how you do it in Java or Python.If you have many parameters, then you can make use of the
argumentsobject, to make things a bit easier:In general,
myChild.prototype = new myClass();is not a good inheritance pattern as most of the time, classes expect some arguments. This won’t execute the parent constructor for each instance but only once for all instances.