Skip to content

Instantly share code, notes, and snippets.

@k33g
Created November 22, 2010 17:41
Show Gist options
  • Save k33g/710319 to your computer and use it in GitHub Desktop.
Save k33g/710319 to your computer and use it in GitHub Desktop.
inheritance of private members in javascript "the return"
Object.prototype.extends = function(p_class){
var instance = new p_class
instance.constructor = this.constructor;
instance.getTypeName = function(){return instance.constructor.name;}
instance.parent = new p_class;
return instance;
}
//Object.prototype.getSelf = function(){return self;}
Object.prototype.new = function(){
var instance = new this;
instance.getTypeName = function(){return instance.constructor.name;}
instance['ctor'].apply(instance,arguments);
return instance;
}
function animal(p){
var self = this;
var note;
var name;
self.getNote=function(){return note}
self.setNote=function(value){note = value}
self.getName=function(){return name;}
self.setName=function(value){name=value;}
/* --- private --- */
test=function(){return 'this is a test';}
/* --- call private --- */
self.callTest=function(){return test();}
self.ctor = function(p){
name = p;
note = "a note from animal";
}
return self;
}
function dog(){
var that = this.extends(animal);
/*--- Private Members ---*/
var specy = "???";
/*--- Public Getters & Setters ---*/
that.getSpecy=function(){return specy}
that.setSpecy=function(value){specy = value}
/*--- Public Method ---*/
that.hello = function(){return 'Hello from '+that.getName();}
/*--- Constructor ---*/
that.ctor = function(p){
that.setName(p)
}
return that;
}
function puppy(){
var self = this.extends(dog);
/* parent ctor is called */
/*self.ctor = function(p){
console.log("*** ctor of dog called ****");
self.setName(p)
}*/
return self;
}
var a = animal.new("BOUBA");
var b = dog.new("Rex");
var c = dog.new("Wolf");
b.setNote("a note from Rex");
b.setSpecy("Berger Belge");
c.setNote("a note from Wolf"); c.setSpecy("Chien Loup");
var d = puppy.new("Junior"); d.setNote("a note from Junior"); d.setSpecy("Caniche");
var e = puppy.new("Germaine"); e.setNote("a note from Germaine"); e.setSpecy("York");
console.log(a.getName()+' '+a.getNote()+' '+a.getTypeName());
console.log(d.getName()+' '+d.getNote()+' '+d.getSpecy());
console.log(e.getName()+' '+e.getNote()+' '+e.getSpecy());
console.log(b.getName()+' '+b.getNote()+' '+b.getSpecy());
console.log(c.getName()+' '+c.getNote()+' '+c.getSpecy());
console.log(b.hello()+' '+b.getTypeName());
console.log(c.hello()+' '+c.getTypeName());
console.log(b.hello()+' '+b.getTypeName());
console.log(d.hello()+' '+d.getTypeName()+' '+d.parent.getTypeName());
console.log(e.hello()+' '+e.getTypeName());
console.log(e.callTest());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment