Difference between 'new person()' and 'prototype.person' in prototype chaining?

55 Views Asked by At
var person = function (name) { 
  this.myName = name;
}
person.prototype.tellMyName = function () {
  console.log(this.myName);
}

var person1 = function (name,age) {
  person.call(this,name);
  this.age = age;
}

//in below line where i'm inheriting prototype properties from parent, both new Person() or person.prototype works
person1.prototype = new person();
person1.prototype.tellMyAge = function () {
  console.log(this.age);
}
var person1Inst = new person1("sadmeer",18);
person1Inst.tellMyName();
person1Inst.tellMyAge();

Apparently i have to call person.call(this,name); in child object constructor to inherit properties in constructor and person1.prototype = new person(); or person1.prototype = person.prototype; to inherit prototype properties.

I wanted to know is that right to use just person1.prototype = person.prototype to inherit properties from parent as i have already inherited properties from constructor??

0

There are 0 best solutions below