Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to assign the JavaScript prototype object instead of just its properties?

In JavaScript we can assign properties to a function's prototype or set its prototype object directly:

var MyClass = function() { };  // The "property" form... MyClass.prototype.foo = function() { ... }; MyClass.prototype.bar = function() { ... }; MyClass.prototype.gah = function() { ... };  // OR the "assignment" form... MyClass.prototype = {   foo:function() { ... },   bar:function() { ... },   gah:function() { ... } }; 

I personally prefer the assignment form because you can easily wrap the object in a closure (e.g. to hide "private" objects) and if you later decide to change the name of "MyClass" you've only got to find two spots instead of potentially dozens. (Of course, the same could be said for the "property" form by using and calling a function which takes the existing prototype as an argument but the "assignment" form seems more direct in my opinion.)

Is there a strong reason to use one form instead of the other?

[Edit]

As commenter @Raynos mentions, the second form (assignment) clobbers the prototype.constructor attribute, which should be set to the MyClass function (and is by default in the first form [property]). Are there any real drawbacks to this (other than the the fact that the property isn't set)?

like image 621
maerics Avatar asked Jun 06 '11 18:06

maerics


People also ask

Can properties be assigned to JavaScript objects?

The same way, JavaScript objects can have properties, which define their characteristics.

Should you use prototype in JavaScript?

You should use prototypes if you wish to declare a "non-static" method of the object. var myObject = function () { }; myObject.

Should I use prototype or class JavaScript?

To answer your question simply, there is no real difference. Straight from the MDN web docs definition: JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance.

Do all JavaScript objects have a prototype property?

Each and every JavaScript function will have a prototype property which is of the object type. You can define your own properties under prototype . When you will use the function as a constructor function, all the instances of it will inherit properties from the prototype object.


1 Answers

The biggest reason not to use the 2nd form is that you'll end up eliminating anything else that existed in the prototype before you assign it. If that isn't something you're concerned with there's no reason not to declare it the way you've demonstrated.

like image 154
g.d.d.c Avatar answered Sep 29 '22 10:09

g.d.d.c