0

I am trying to understand How I can do inheritance in JavaScript properly. I can see that in many sources They do it using the create method as follows:

var ClassA = function() {
this.name = "class A";
}


ClassA.prototype.print = function() {
console.log(this.name);
}


var ClassB = function() {
this.name = "class B";
this.surname = "I'm the child";
}

ClassB.prototype = Object.create(ClassA.prototype);
....

However, I can see that I can extend from the parent object (ClassA) without using the create method, like that:

ClassB.prototype = ClassA.prototype;

So, Could Anyone tell me, why should I use the "Create" global method, as many examples do? In addition, in many examples They call the constructor of the base class (ClassA.call(this)), but I can see it is not really necessary. So?, I would appreciate your ideas. Thanks.

D.B
  • 4,009
  • 14
  • 46
  • 83
  • 1
    http://stackoverflow.com/questions/25588255/can-modifying-the-prototype-on-a-child-affect-the-parents-prototype – christophe.chapron Sep 26 '15 at 13:28
  • If you add a method to ClassB's prototype, it will also be added to ClassA's prototype as they reference the same object. Using Object.create creates a new object so adding methods to ClassB's prototype will not affect ClassA's prototype. – Ben Guest Sep 26 '15 at 13:28
  • Try to give `ClassB` its own `print` method and see it fail without `Object.create`. – Bergi Sep 26 '15 at 13:30
  • Thank you. your answers were precise and concise. Likewise, I could get a deeper information in the other question already asked. – D.B Sep 26 '15 at 14:07

0 Answers0