Javascript Inheritance (infinite Loop When Using Superclass Function)
Solution 1:
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
isPerson.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
.
Post a Comment for "Javascript Inheritance (infinite Loop When Using Superclass Function)"