JavaScript: Example of Inheritance
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
Person.prototype.getFullName = function () {
console.log(`${this.firstname} ${this.lastname}`);
};
var obama = new Person('Barack', 'Obama');
console.log(obama.__proto__ === Person.prototype);
obama.getFullName();
function Engineer(firstname, lastname, field) {
Person.call(this, firstname, lastname);
this.field = field;
}
Engineer.prototype = Object.create(Person.prototype);
Engineer.prototype.constructor = Engineer;
Engineer.prototype.getDescription = function () {
console.log(`I'm a ${this.field} engineer.`);
};
var dan = new Engineer('Dan', 'Abramov', 'software');
console.log(dan.__proto__ === Engineer.prototype);
dan.getFullName();
dan.getDescription();