Home >Web Front-end >JS Tutorial >What are the Differences Between Extending and Overwriting JavaScript Prototypes?
Defining a JavaScript Prototype: Exploring Two Syntaxes and their Impacts
In JavaScript, defining prototypes offers a convenient way to add behavior to objects. Two common syntaxes exist for prototype definition, and they can have functional differences.
Option 1: Extending the Existing Prototype
Person.prototype.sayName = function(name) { alert(name); }
This syntax extends the existing prototype object with a new property (sayName) and a function assigned to it. Objects instantiated before this definition can inherit the new method.
Option 2: Overwriting the Prototype
Person.prototype = { sayName: function(name) { alert(name); } }
Here, the entire prototype object is replaced with a new one, containing only the sayName method. This overwrites all existing prototype properties, including the implicitly bound constructor property.
Functional Differences
Benefits and Drawbacks
Alternative Syntax for Extending:
For a cleaner object literal syntax without overwriting, consider using Object.assign:
Object.assign(Person.prototype, { sayName: function(name) { alert(name); } });
The above is the detailed content of What are the Differences Between Extending and Overwriting JavaScript Prototypes?. For more information, please follow other related articles on the PHP Chinese website!