Home > Article > Web Front-end > Extending vs. Overwriting JavaScript Prototypes: Which Approach is Best?
Defining a JavaScript Prototype: Understanding the Differences
Defining object prototypes in JavaScript is essential for inheritance and code reusability. However, there are two common approaches to prototype definition: extending the existing prototype or overwriting it entirely.
Option 1: Extending the Existing Prototype
Person.prototype.sayName = function(name) { alert(name); }
This approach extends the current prototype object Person.prototype by adding a new method sayName. Existing instances of Person will inherit this new method.
Option 2: Overwriting the Prototype
Person.prototype = { sayName: function(name) { alert(name); } }
Unlike Option 1, this approach assigns a new prototype object to Person.prototype, overwriting the original one. Only future instances of Person will inherit the sayName method.
Functional Differences and Benefits
The primary functional difference is that Option 1 allows existing instances to access the new method, while Option 2 only affects future instances.
Another difference is that by overwriting the prototype (Option 2), you inadvertently discard any other properties or methods previously defined in the original prototype. Although these typically include only the constructor property, it's worth noting this potential downside.
Recommendation
Option 1 (extending) is generally considered more concise and robust as it ensures that all instances of Person can access sayName. Avoid Option 2 unless you need to reinitialize the prototype for specific reasons.
Alternative Approach
If the object literal syntax of Option 2 appeals to you, consider using Object.assign to extend the existing prototype:
Object.assign(Person.prototype, { sayName: function(name) { alert(name); } });
The above is the detailed content of Extending vs. Overwriting JavaScript Prototypes: Which Approach is Best?. For more information, please follow other related articles on the PHP Chinese website!