Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a Javascript prototype

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?

like image 946
Richard Keller Avatar asked Jul 04 '13 15:07

Richard Keller


1 Answers

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.

like image 164
Bergi Avatar answered Oct 16 '22 14:10

Bergi