I'm trying to get my head around JS inheritance using the "Pseudo-classical inheritance" style. I've done many Google searches and have read the classic articles. I'm familiar with Java's class structure and am trying to understand JS's prototypal style. I'm looking for vanilla JS since I want to understand the basics first.
I have a simple parent/child test class setup and need some help with the scoping rules.
1.) When do I define methods in the class vs outside of the class?
2.) How do I access private variables and private functions when I create methods using the prototype style?
function superClass(name){
this.name = name;
var privateValue = "I'm Private";
this.outputPrivate2 = function(){
alert(privateValue); //works fine
}
}
superClass.prototype.outputPrivate = function(){
alert(this.privateValue); //outputs undefined..
alert(superClass.prototype.privateValue) //also undefined
}
3.) How Can child objects call private functions or access private variables of the parent?
4.) When should the child object manually call the parent constructor?
subClass2.prototype = new superClass(); // Define sub-class
subClass2.prototype.constructor = subClass2;
function subClass2(name) {
this.name = name;
this.Bye = function() {
return "Bye from subClass - " + this.name;
}
this.testm = function(){
superClass.prototype.SomeParentMethod.call(this, "arg1", "arg2");
}
}
var parent = new superClass("parent");
var child = new subClass("child1");
parent.outputPrivate(); //undefined
parent.outputPrivate2(); //I'm private
child.outputPrivate(); //undefined
child.outputPrivate2(); //I'm private
I had three objects where 80% of the code was duplicated so I created a parent object and three child objects. The child objects have methods that use and manipulate private data from the parent. The only way I've gotten this to work is make all variables public which I don't like. Again, my familiarity is with Java so I might be trying too hard to make JS work like Java.