2

what is the difference between Person.prototype and Object.create(Person.prototype) ? Could I use each of them?

function Person(name) {
    this.name = name;
}  

Person.prototype.copy = function() {  
    return new this.constructor(this.name);
};  

// define the Student class  
function Student(name) {  
    Person.call(this, name);
}  

// inherit Person  
Student.prototype = Person.prototype;
//Student.prototype = Object.create(Person.prototype);
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Oleg alex
  • 99
  • 6
  • http://blog.slaks.net/2013-09-03/traditional-inheritance-in-javascript/ – SLaks Jul 19 '15 at 15:20
  • 2
    See also: [Using “Object.create” instead of “new”](http://stackoverflow.com/q/2709612/4639281) –  Jul 19 '15 at 15:25

1 Answers1

6

It is better to use Student.prototype = Object.create(Person.prototype) instead of Student.prototype = Person.prototype;

the reason being in the later case both prototype share a common object. So wen we add a new method in Student prototype , person prototype will also be accessed to that property. eg:-

Student.prototype = Person.prototype
Student.prototype.test = function(){ alert('in student');};
var person = new Person();
person.test();

this will alert 'in student'

abs
  • 801
  • 6
  • 15
  • To me with your code and **Student.prototype = Object.create(Person.prototype)** also alerts to 'in student'. So they are sharing the same reference. So, what's the difference then? – Oleg alex Jul 19 '15 at 15:31
  • 1
    Can you try this if you are getting the alert function Student(){} function Person(){} Student.prototype = Object.create(Person.prototype); Student.prototype.test = function(){ alert('in student');}; var person = new Person(); person.test(); – abs Jul 19 '15 at 15:35
  • 1
    @Olegalex: that is not possible, you can't just get the same result with and without Object.create. – Wiktor Zychla Jul 19 '15 at 15:39
  • @WiktorZychla I have the same result here with Firefox. Both variants alerts the student : ` function Person(name) { this.name = name; } Person.prototype.copy = function () { return new this.constructor(this.name); }; // define the Student class function Student(name) { Person.call(this, name); } // inherit Person Student.prototype = Person.prototype; //Student.prototype = Object.create(Person.prototype); Student.prototype = Person.prototype Student.prototype.test = function () { alert('in student'); }; var person = new Person(); person.test(); ` – Oleg alex Jul 19 '15 at 15:45
  • @Olegalex: you are not. Check this fiddle https://jsfiddle.net/3rrct5rk/ – Wiktor Zychla Jul 19 '15 at 16:10
  • @Olegalex: I believe you have an additional prototype reference copying just after Object.create. Basically then your both versions do the same. I removed this invalid line from the fiddle. – Wiktor Zychla Jul 19 '15 at 16:13
  • @WiktorZychla yes, that was the reason, a typo. Thanks! – Oleg alex Jul 19 '15 at 18:06