原型上的Javascript私有成员

Paw*_*phy 17 javascript prototype private

好吧,我试图弄清楚这有可能以任何方式.这是代码:

a=function(text)
{
   var b=text;
   if (!arguments.callee.prototype.get)
      arguments.callee.prototype.get=function()
    {
         return b;
    }
    else
      alert('already created!');
}

var c=new a("test");  // creates prototype instance of getter
var d=new a("ojoj");  // alerts already created
alert(c.get())        // alerts test 
alert(d.get())        // alerts test from context of creating prototype function :(
Run Code Online (Sandbox Code Playgroud)

如你所见,我试图创建原型getter.为了什么?好吧,如果你写这样的东西:

a=function(text)
{
    var b=text;
    this.getText=function(){ return b}
}
Run Code Online (Sandbox Code Playgroud)

......一切都应该没问题......但实际上每次创建对象时 - 我都会创建使用内存的getText函数.我想在记忆中有一个原型功能可以做同样的事情...任何想法?

编辑:

我试过Christoph给出的解决方案,它似乎是目前唯一已知的解决方案.它需要记住id信息以从上下文中检索值,但是整个想法对我来说很好:) Id只是要记住的一件事,其他一切都可以在内存中存储一​​次.实际上,您可以通过这种方式存储许多私有成员,并且只能使用一个id.实际上这让我很满意:)(除非有人有更好的主意).

someFunc = function()
{
  var store = new Array();
  var guid=0;
  var someFunc = function(text)
  {
    this.__guid=guid;
    store[guid++]=text;
  }

  someFunc.prototype.getValue=function()
  {
    return store[this.__guid];
  }

  return someFunc;
}()

a=new someFunc("test");
b=new someFunc("test2");

alert(a.getValue());
alert(b.getValue());
Run Code Online (Sandbox Code Playgroud)

Chr*_*oph 28

JavaScript传统上没有提供属性隐藏机制('私有成员').

由于JavaScript是词法范围的,你可以使用构造函数作为对"私有成员"的闭包并在构造函数中定义方法,从而在每个对象级别上模拟这个,但这不适用于在构造函数的原型属性.

当然,有办法解决这个问题,但我不推荐它:

Foo = (function() {
    var store = {}, guid = 0;

    function Foo() {
        this.__guid = ++guid;
        store[guid] = { bar : 'baz' };
    }

    Foo.prototype.getBar = function() {
        var privates = store[this.__guid];
        return privates.bar;
    };

    Foo.prototype.destroy = function() {
        delete store[this.__guid];
    };

    return Foo;
})();
Run Code Online (Sandbox Code Playgroud)

这会将"私有"属性存储在与您的Foo实例分开的另一个对象中.确保destroy()在完成对象后调用:否则,您刚刚创建了内存泄漏.


编辑2015年12月1日: ECMAScript6使得不需要手动物件破坏可能的,例如通过使用改进的变体WeakMap或优选符号,避免了对外部存储完全的需要:

var Foo = (function() {
    var bar = Symbol('bar');

    function Foo() {
        this[bar] = 'baz';
    }

    Foo.prototype.getBar = function() {
        return this[bar];
    };

    return Foo;
})();
Run Code Online (Sandbox Code Playgroud)