Inheritance in Javascript
Inheritance in Javascript
Inheritance is when an object or class is based on another object (prototypal inheritance) or class (class-based inheritance), using the same implementation.
function Person(name, age, gender, interests) {
this.name = name
this.age = age;
this.gender = gender;
this.interests = interests;
this.getName = function() {
return this.name;
}
};
Person.prototype.getAge = function() {
return this.age;
}
/**
Teacher inherit properties from the person class.
Person.call(this, name, age, gender, interests )
after .call() properties are inherited in teacher class.
*/
function Teacher(name, age, gender, interests, subject) {
Person.call(this, name, age, gender, interests)
// Vehicle.call(this)
this.subject = subject;
this.getSubject = function() {
return this.subject;
}
this.getName = function() {
return 'MR ' + this.name;
}
};
var teacher = new Teacher('kumar', 23, 'male', 'sports', 'English')
console.log(teacher)
console.log(teacher.getName())
/**
To subclass extends superclass prototype properties
*/
Teacher.prototype = Object.create(Person.prototype)
Multilevel inheritance
var Vehicle = function() {
this.seats = 0;
}
function Car() {
this.wheels = 4
}
Car.prototype.getWheels = function() {
return this.wheels;
}
function Honda() {
this.model = '2017'
}
//Multilevel inheritance
Honda.prototype = Object.create(Vehicle.prototype)
Object.assign(Car.prototype, )
var car = new Car;
console.log('Car', car.getWheels())
/**
Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
*/
Comments
Post a Comment