JS prototype vs closure

I have a JavaScript object that does something like this - using a 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 be creating around 4000 instances of this object, and from what I am reading adding functions via the prototype will be more efficient than adding them as I have above (because in my example, each instance will have it's own getXYProcust() , getNegX() and getNegY() functions.

My question is twofold - is my approach above really "inefficient"? I realize that inefficient is a relative term - but is this something I will likely notice. If it is inefficient, how would I add those functions to the prototype of 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 inspect it.

Thanks in advance for any help - I appreciate it!


  • The best advice is to try it and see . In the modern JS engines, you should find that 4,000 objects are childs play and should not be a problem (provided each of them don't get too big). If you've got users on IE6 and older engines, be prepared for them to be able to cope with less.

    As an example, a Facebook Timeline feed requires ~4000 (3992 when I tried) DOM elements; each of these are far more complicated than the objects you're creating (granted, they make use of the prototype method, but they hold a lot more information).

  • You cannot apply the private member pattern when using prototype 's, because you cannot create a closure to encapsulate both. The typical pattern here is to denote a private member with a leading _ , to hint at people not to use it (but of course, there is nothing stopping them from doing so).

  • 链接地址: http://www.djcxy.com/p/10436.html

    上一篇: 如何在多个项目之间共享多个文件时使用GIT

    下一篇: JS原型vs封闭