I’m doing some experiences with OOP in JavaScript. My goal is to have a parent object which holds methods common to several other objects, which inherit from that parent object. Thing is, I want the parent objects’ methods to be able to read the childrens’ fields.
I use the following function for inheritance:
Function.prototype.inherits=function(obj){this.prototype=new obj();}
These are some example objects:
function Genetic(c){
this.code=c;
}
//My 'parent object':
function Animal(){
this.getCode=function(){
return(genetic.code);
}
}
g=new Genetic('test');
function Dog(){
genetic=g;
}
Dog.inherits(Animal);
g=new Genetic('foo');
function Cat(){
genetic=g;
}
Cat.inherits(Animal);
d=new Dog();
c=new Cat();
Now, I expect d.getCode() to return 'test', and c.getCode() to return 'foo'. Problem is, both return 'foo'. The variable genetic is in the Animal scope, and not in the Dog/Cat scope. Meaning that whenever I create a new object that inherits from Animal, the genetic variable will be overridden. Proof:
function Bla(){}
Bla.inherits(Animal);
bla=new Bla()
bla.getCode() //Returns 'foo'
I can set the genetic variable to being a private variable of Dog and Cat with var:
function Dog(){
var genetic=g;
}
Problem is, since genetic is now private to Dog, it can’t be accessed by the Animal object, rendering the whole inheritance pointless.
Do you see any way to solve that?
EDIT: Also, I want gentic to be private, so that it can’t be modified in Dog/Cat instances.
No,
geneticis global. There exists only onegeneticvariable in your whole application. Make it a property of the object.Furthermore, a better way of inheritance is the following:
Then you can have the parent constructor accept arguments and don’t have to repeat code:
I would advice to document your code properly and rather follow a clear prototype/inheritance chain than trying to do something the language is not designed for.
However, with the
inheritsfunction given above, you could do:with the rest of the code staying the same. Then you have your “private” variable at the cost of every instance having its own
getCodefunction.Edit: This would not let you access
geneticin any function assigned toDogorCat, unless you also keep a reference to the value in their constructors.