Skip to content

Instantly share code, notes, and snippets.

@nsisodiya
Created July 20, 2012 08:40
Show Gist options
  • Save nsisodiya/3149660 to your computer and use it in GitHub Desktop.
Save nsisodiya/3149660 to your computer and use it in GitHub Desktop.
/* Author : Narendra Sisodiya
* Date : Thu Jul 19 18:16:38 IST 2012
* Licence : Public Code
* Purpose : Inheritance
*
* Function.prototype.inheritFrom & NewClass.prototype._super
* It will not work for Manager Class
* Run in Chrome ---
*/
Function.prototype.inheritFrom = function (Base){
var F = function(){};
F.prototype = Base.prototype;
var old_prototype = this.prototype;
this.prototype = new F();
this.prototype.constructor = this;
for (i in old_prototype) {
this.prototype[i] = old_prototype[i];
}
this.prototype._super = function (){
if(arguments.length >= 1 ){
Base.apply(this, arguments);
}else{
Base.call(this);
}
}
}
var Person = function(full_name, age) {
this.full_name = full_name;
this.age = age;
}
Person.prototype = {
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;
}
};
var Employee = function(full_name, age, job_title){
this._super(full_name, age);
this.job_title = job_title;
};
Employee.prototype = {
office: function(){
console.log(this.full_name + " is a "+ this.job_title + " and he is going to Office");
return this;
}
};
Employee.inheritFrom(Person);
var Manager = function(full_name, age, job_title, dept){
this._super(full_name, age, job_title);
this.dept = dept;
};
Manager.prototype = {
presentation: function(){
console.log(this.full_name + " is a Manager of " + this.dept + " Department and he is doing presentiation");
return this;
}
};
Manager.inheritFrom(Employee);
var deepak = new Person("Deepak", 17, "Student");
deepak.eat().drive();
var narendra = new Employee("Narendra", 30, "Engineer");
narendra.eat().drive().office();
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