Skip to content

Instantly share code, notes, and snippets.

@nsisodiya
Created August 23, 2012 11:49
Show Gist options
  • Save nsisodiya/3435891 to your computer and use it in GitHub Desktop.
Save nsisodiya/3435891 to your computer and use it in GitHub Desktop.
JavaScript Prototypal Inheritance with Private function and Private-Static properties
/* Author : Narendra Sisodiya
* Date : Thu Jul 19 18:16:38 IST 2012
* Licence : Public Code
* Purpose : Inheritance
* Multilevel JavaScript Prototypal Inheritance
*/
function inherit(Child){
return {
"from": function(Parent){
var old_prototype = Child.prototype;
/*var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();*/
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
for (i in old_prototype) {
Child.prototype[i] = old_prototype[i];
}
Child.parent = Parent;
}
}
}
var Person = function(full_name, age) {
this.full_name = full_name;
this.age = age;
}
Person.prototype = (function(){
//Private Function
var talkToWife = function(){
console.log("I love you");
};
//Private-Static properties
// All objects has access to this property via public functions
var x ;
//Public Function
return {
drive: function() {
if(this.age >= 18){
console.log(this.full_name + " is driving");
}else{
console.log(this.full_name + " is not eligible for driving");
}
return this;
},
eat: function(){
console.log(this.full_name + " is eating");
return this;
},
talk: function(){
talkToWife();
return this;
},
setx: function(_x){
x = _x;
return this;
},
getx: function(){
console.log("x is " + x);
return this;
},
};
})();
var Employee = function(full_name, age, job_title){
Employee.parent.call(this,full_name, age);
this.job_title = job_title;
};
Employee.prototype = (function(){
var x = 2;
return {
office: function(){
console.log(this.full_name + " is a "+ this.job_title + " and he is going to Office");
return this;
}
};
})();
inherit(Employee).from(Person);
var Manager = function(full_name, age, job_title, dept){
Manager.parent.call(this, full_name, age, job_title);
this.dept = dept;
};
Manager.prototype = (function(){
return {
presentation: function(){
console.log(this.full_name + " is a Manager of " + this.dept + " Department and he is doing presentiation");
return this;
}
};
})();
inherit(Manager).from(Employee);
var deepak = new Person("Deepak", 17);
deepak.eat().drive().talk().getx().setx(30).getx();
var suresh = new Person("suresh", 17);
suresh.eat().drive().talk().getx().setx(100).getx();
deepak.getx();
var narendra = new Employee("Narendra", 30, "Engineer");
narendra.eat().drive().office();
narendra.getx();
var chetan = new Manager("Chetan", 24, "Doctor", "Research");
chetan.eat().drive().office().presentation();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment