Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

7
  • 2
    Never. ever. assign to prototype properties from within your constructor. Commented Apr 7, 2016 at 23:32
  • @Bergi Thanks for the comment... I keep hearing this cliche time to time yet neither could think of a justifiable reason myself nor heard anybody talking more than this sentence. I tend to believe it's nothing more than a gossip in the air. Could you please elaborate me on what are the dangers of adding two tiny functions to the prototype of a function that's also created by myself. Commented Apr 8, 2016 at 9:13
  • It's not a cliche: it just doesn't make sense, and it has undesirable behaviour. You already seem to understand this, as you named that class "SharedPrivate", and even seem to expect the usually undesired behaviour where o1 interferes with o2; but even if you want to create a static, shared variable your approach doesn't work. Just try to create an o3 somewhere in that sequence of calls… The problem is not with adding to the prototype, but with doing so in the constructor. Commented Apr 8, 2016 at 10:35
  • Thank you for taking your time to explain. My bad.. i forgot to mention that my critic to the "Never. ever. assign to prototype properties from within your constructor" sentence was only related as per the pattern i have shown above. Otherwise of course you shouldn't modify the prototype from within the constructor. However, makes sense or not, if you need to create a shared private among several objects, then they have to be created at once together since as you have also figured out. There is no way to do this with a constructor without touching the prototype within itself. Commented Apr 8, 2016 at 11:01
  • No, the sentence did not just relate to your specific code. There really is never a good reason to do that - "Otherwise of course you should modify the prototype from within the constructor." is plainly wrong. Or can you name a reason? If you want to share state across instances, you shouldn't create that state in (the last call of) the constructor. Just put it outside of the constructor, and wrap everything in an IIFE if you need privacy. Commented Apr 8, 2016 at 11:07