Created
August 23, 2012 11:18
-
-
Save nsisodiya/3435680 to your computer and use it in GitHub Desktop.
JavaScript Prototypal Inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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 = { | |
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){ | |
Employee.parent.call(this,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; | |
} | |
}; | |
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 = { | |
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(); | |
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