Sunday, December 21, 2014

Prototypal Inheritance in JavaScript

Prototypal Inheritance in JavaScript

function Person(name, place) {
this.name = name;
this.place = place;
}
Person.prototype = {
getName : function() {
return this.name;
},
setName : function(name) {
this.name = name;
}
};
Person.prototype.constructor = Person;
function Employee(id, job, name, place) {
Person.call(this, name, place);
this.id = id;
this.job = job;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.getJob = function() {
return this.job;
};
Employee.prototype.setJob = function(job) {
this.job = job;
};
var e1 = new Employee(121, "JS", "Deepak", "Delhi");
console.log(e1.getName()); // "Deepak"
e1.setName("Chetan");
console.log(e1.getName()); // "Chetan"
console.log(e1.getJob()); // "JS"
e1.setJob("JavaScript Developer");
console.log(e1.getJob()); // "JavaScript Developer"
view raw gistfile1.js hosted with ❤ by GitHub
Link 1 - Prototypal Inheritance

No comments:

Post a Comment