JS prototype against closure

I have a JavaScript object that does something like this - using closure to simulate private vs public functions / variables:

var myCoolObject = function(x, y) { var prop1 = "a cool prop1 value"; var negX = x * -1; var negY = y * -1; var xyProduct = x * y; return { PublicProp1: prop1, getXYProduct: function() { return xyProduct; }, getNegX: function() { return negX; }, getNegY: function() { return negY; } } } 

I will create about 4000 instances of this object, and from what I read, adding functions via prototype will be more efficient than adding them, as I above (because in my example each instance will have its own getXYProcust() , getNegX() and getNegY() .

My question is twofold - is my approach above really "ineffective"? I understand that an ineffective relative term is what I’m most likely to notice. If this is inefficient, how would I add these functions to the prototype from myCoolObject ? I tried the following:

 myCoolObject.prototype.protoProp = "pppp"; myCoolObject.prototype.getAtMeBro = function () { return "get at me bro"; }; var myInstance = new myCoolObject(5, 10); 

But neither protoProp nor 'getAtMeBro ()' are properties of myInstance when I check it.

Thanks in advance for any help - I appreciate it!

+7
source share
1 answer
  • The best advice is to try and see . In modern JS engines, you should find that 4,000 objects are games for children and should not be a problem (provided that each of them does not become too big). If you have users in IE6 and earlier, be prepared to handle less.

    As an example, a Timeline feed for Facebook requires ~ 4000 (3992 when I tried) DOM elements; each of them is much more complicated than the objects you create (they are provided, they use the prototype method, but they contain much more information).

  • You cannot apply the private member pattern when using prototype , because you cannot create a closure to encapsulate both. A typical example here is to designate a private member with a leading _ , in order to hint that people will not use it (but, of course, there is nothing that will prevent them from doing this).

+3
source

All Articles