Created
February 23, 2016 09:54
Classical Inheritance in Javascript
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
//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