0

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

2
  • What is the difference between the two lines? Commented Dec 5, 2012 at 10:12
  • Did you mean Employee.prototype = Person.prototype; (from the fiddle)? Commented Dec 5, 2012 at 10:14

1 Answer 1

2

If you do (as shown in the fiddle)

Employee.prototype = Person.prototype;

then Employee will not be a subclass of Person, 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 Employee will be also visible for any Person. Note that classes in OOP should not affect their superclass in any way.


Employee.prototype = Object.create(Person.prototype);

will create a new Object, similarly to

Employee.prototype = {};
Employee.prototype.__proto__ = Person.prototype

except Object.create (unlike __proto__) works in all browsers, or to

Employee.prototype = new Person();

except the constructor of Person may also set additional properties to Employee.prototype while Object.create will create an object without extra properties.


The infinite loop in your fiddle happens because Employee.prototype.sayHi calls Person.prototype.sayHi, but Employee.prototype.sayHi is Person.prototype.sayHi, and thus it calls itself (the original Person.prototype.sayHi was lost when you assigned to Employee.prototype.sayHi).

If Employee.prototype === Person.prototype then, neccessarily, Employee.prototype.sayHi === Person.prototype.sayHi.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.