Prototypes are an excellent way to conserve memory by allowing failed property lookups, such as methods (see below), to traverse the object’s prototype chain. Put another way, if we invoke a method on an object, but that method does not exist on that object, then the failed lookup doesn’t stop there. Instead, it will traverse the prototype chain until the method is found or, if eventually not found, an error is thrown. One advantage to this is that we as developers don't have to rewrite (or debug) multiple occurrences of the same method.
Consider the following:​​​​​​​
JavaScript will look in the current object for the sayHello method. In the case of cassandra and dimitri, there is an initial failed lookup. But because we used Object.create() in the Person constructor function, the failed lookup continues to traverse up the prototype chain to Person.prototype, where sayHello is found. On the other hand, for jose, we did not define sayHello within its prototype chain. Therefore, the invocation evaluates to a TypeError.

You may also like

Back to Top