What are the functional differences between the following two Javascript prototypes, and are there any benefits for choosing one over the other?
Option 1:
Person.prototype.sayName = function(name) {
alert(name);
}
Option 2:
Person.prototype = {
sayName: function(name) {
alert(name);
}
}
Am I correct in assuming that Option 2 results in trashing certain functions that are implicitly bound to the prototype?
Am I correct in assuming that Option 2 results in trashing certain functions that are implicitly bound to the prototype?
Yes, exactly. Though the only implicitly bound property is the constructor
property, which you seldom do need.
What are the functional differences?
Option 1 is just extending the existing prototype. If there are already Person
instances inheriting from the prototype object, they will be able to use the sayName
method as well. With option 2, the new prototype will only be used for objects that are instantiated after the overwriting.
Are there any benefits for choosing one over the other?
These should be self-explaining now. Option 1 (extending) is considered cleaner, and is a must if you're modifying foreign/unknown/native prototypes. Try to avoid option 2.
If you still like the object literal syntax better, you should consider using Object.assign
to extend the existing prototype:
Object.assign(Person.prototype, {
sayName: function(name) {
alert(name);
}
});
You may need to polyfill Object.assign
for pre-ES6 environments. Alternatively, $.extend
or _.extend
work just as well. Surely also your favourite library comes with a helper function for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With