Skip to content

Instantly share code, notes, and snippets.

@deepakkj
Created February 23, 2016 09:54
Show Gist options
  • Save deepakkj/5c7d87db93ed6918cfad to your computer and use it in GitHub Desktop.
Save deepakkj/5c7d87db93ed6918cfad to your computer and use it in GitHub Desktop.
Classical Inheritance in Javascript
//parent
var Person = function(firstName){
this.firstName = firstName;
};
Person.prototype.walk = function(){
console.log("I am walking.");
};
Person.prototype.sayHello = function(){
console.log("I am " + this.firstName);
};
//child
function Student(firstName, subject){
Person.call(this, firstName);
this.subject = subject;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.sayHello = function(){
console.log("Student\'s name is " + this.firstName);
};
Student.prototype.study = function(){
console.log(this.firstName + " is studying");
};
var p1 = new Person("Deepak");
var p2 = new Person("Mohan");
p1.sayHello();
p1.walk();
p2.sayHello();
p2.walk();
var s1 = new Student("Jitesh");
var s2 = new Student("Vineeth");
s1.sayHello();
s1.study();
s2.sayHello();
s2.study();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment