Last active
August 29, 2015 14:22
-
-
Save baskeboler/62524ff2f62b7c93afb0 to your computer and use it in GitHub Desktop.
Javascript inheritance and polymorphism
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
var Person = function (name) { | |
this.name = name; | |
} | |
Person.prototype = { | |
sayHi: function() { | |
console.log('Hi, my name is ' + this.name); | |
}, | |
parentClassMethod: function() { | |
console.log('Method from Person class called on ' + this.name); | |
} | |
}; | |
var Student = function(name, carreerPath) { | |
Person.call(this, name); // call parent constructor | |
this.carreerPath = carreerPath; | |
}; | |
Student.prototype = Object.create(Person.prototype); //inherit parent prototype object | |
Student.prototype.constructor = Student; //overwrite constructor | |
Student.prototype.sayHi = function() { //override sayHi function | |
console.log('Hi, I am ' + this.name + ' and I study ' + this.carreerPath); | |
}; | |
var person = new Person('John'); | |
person.sayHi(); | |
person.parentClassMethod(); | |
var student = new Student('Ramon', 'Engineering'); | |
student.sayHi(); | |
student.parentClassMethod(); | |
if (student instanceof Person) { | |
console.log('Student is instance of Person'); | |
} | |
if (student instanceof Student) { | |
console.log('Student is instance of Student'); | |
} | |
if (person instanceof Person) { | |
console.log('person is instance of Person'); | |
} | |
if (person instanceof Student) { | |
console.log('person is instance of Student'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment