0
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??

SameerShaik
  • 488
  • 2
  • 10
  • 22
  • 1
    `person1.prototype = new person()` is NOT the correct way of inheriting. It should be `person1.prototype = Object.create(person.prototype)` and then you have to set the constructor property of the prototype back to the original: `person1.prototype.constructor = person1`: [Benefits of using Object.create for inheritance](https://stackoverflow.com/q/17392857) – adiga Dec 19 '20 at 11:28
  • `person1.prototype = person.prototype` is also incorrect because: [What is the difference o1.prototype = Object.create(o2.prototype) and o1.prototype = o2.prototype?](https://stackoverflow.com/q/57127249) – adiga Dec 19 '20 at 11:32

0 Answers0