Skip to content

Instantly share code, notes, and snippets.

@baskeboler
Last active August 29, 2015 14:22
Show Gist options
  • Save baskeboler/62524ff2f62b7c93afb0 to your computer and use it in GitHub Desktop.
Save baskeboler/62524ff2f62b7c93afb0 to your computer and use it in GitHub Desktop.
Javascript inheritance and polymorphism
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