I am viewing Tuts+ OO JavaScript training: The way they do prototypical inheritance looks like:
Employee.prototype = Object.create(Person.prototype);
But why cant I do just (without object create)
Employee.prototype = Person.prototype;
The 2nd will give an infinite loop: http://jsfiddle.net/VMqSy/
Why? Console logging the prototypes tells me that the 1 with Object.create() will give Employee.prototype 1 more level of __proto__ which is the Person.prototype, I think
If you do (as shown in the fiddle)
then
Employeewill not be a subclass ofPerson, but rather they will become the same class (albeit with two different constructors).More exactly, the methods and properties that you add to the prototype of
Employeewill be also visible for anyPerson. Note that classes in OOP should not affect their superclass in any way.will create a new Object, similarly to
except
Object.create(unlike__proto__) works in all browsers, or toexcept the constructor of
Personmay also set additional properties toEmployee.prototypewhileObject.createwill create an object without extra properties.The infinite loop in your fiddle happens because
Employee.prototype.sayHicallsPerson.prototype.sayHi, butEmployee.prototype.sayHiisPerson.prototype.sayHi, and thus it calls itself (the originalPerson.prototype.sayHiwas lost when you assigned toEmployee.prototype.sayHi).If
Employee.prototype === Person.prototypethen, neccessarily,Employee.prototype.sayHi === Person.prototype.sayHi.