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 working at Integ
Notice that we are calling Person function from Employee constructor function using Employee's this. This way whatever initializing properties of Person will be initialized and assigned to Employee's this. So Whatever properties should be in Person's object we have it in Employee's object.
Now, properties assigned to Person.prototype we need to get that too. To do so we assigned Person.prototype to Employee.prototype.__proto__. This creates prototype chain of emp object like below and emp object can access properties of Person.prototype though the chain.
emp
|---- __proto__ === Employee.prototype
|---- __proto__ === Person.prototype
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 working at Integ
Notice that we are calling Person function from Employee constructor function using Employee's this. This way whatever initializing properties of Person will be initialized and assigned to Employee's this. So Whatever properties should be in Person's object we have it in Employee's object.
Now, properties assigned to Person.prototype we need to get that too. To do so we assigned Person.prototype to Employee.prototype.__proto__. This creates prototype chain of emp object like below and emp object can access properties of Person.prototype though the chain.
emp
|---- __proto__ === Employee.prototype
|---- __proto__ === Person.prototype
Comments
Post a Comment