Skip to main content

Posts

Showing posts with the label inheritance

Inheritance with constructor function in javascript

Object literal like var derived = {     a: 10 }; be easily extended using derived.__proto__ = base; where base is var base = {     x : 5 }; But, what if we using constructor function? We need to do like this var Person = function (name) {     this.name = name; } Person.prototype.sayHello = function () {     console.log('Hello, I am '+this.name); } Person.prototype.getName = function () {     return this.name; } var per = new Person('Manan'); per.sayHello(); //prints --> Hello, I am Manan var Employee = function (name, company) {     Person.call(this, name);     this.company = company; } Employee.prototype.sayHello = function () {     console.log('Hello, I am '+this.getName()+' and I am working at '+this.company); } Employee.prototype.__proto__ = Person.prototype; var emp = new Employee('Manan', 'Integ'); emp.sayHello(); //prints --> Hello, I am Manan and I am workin...