【问题标题】:JavaScript: Private variables in prototype functionJavaScript:原型函数中的私有变量
【发布时间】:2013-08-02 14:45:54
【问题描述】:

我正在使用原型函数,因为当“类”被多次实例化时,它们应该具有更好的性能。此外,并非所有变量都应该可供外部访问,因此它们是通过var 在“类”内定义的,因此在闭包空间之外的任何地方都无法访问它们。

现在我有了这个简单的例子,我在其中定义了一个“私有”变量并为它定义了 set 和 get 函数。

例子:

function Test() {
    var hello = "org";

    this._get = function (value) {
          hello = value;
    }
    this._set = function (value) {            
         return hello;            
    }
}


var test = new Test();
console.log(test._get());
test._set("new");
console.log(test._get());

提琴手:http://jsfiddle.net/LdwuS/

现在我想对原型做同样的事情,但 get 函数总是返回 undefined!

例子:

function Test() {
    var hello = "org";
}

Test.prototype.set = function (value) {
    return hello;
}
Test.prototype.get = function (value) {
    hello = value;
}

var test = new Test();
console.log(test.get());
test.set("new");

提琴手:http://jsfiddle.net/rK22m/

我做错了什么还是不可能? console.log(test.get());

【问题讨论】:

  • 无法从函数外部定义的函数访问函数内部定义的变量。这包括.prototype 上的功能。
  • ...在第二个示例中,您的 setget 行为颠倒了。
  • ECMAScript 6 可能会定义对属性的“键控”访问,您可以在其中需要键来访问某些属性,提供对象上的私有成员之类的东西。
  • 这已经是可能的(只需使用一些随机生成的字符串作为键),但是将可以静态强制执行的东西带到运行时是荒谬的

标签: javascript prototype


【解决方案1】:

与原型对象相关联的函数与任何其他函数对对象的访问方式完全相同。此外,与其他函数一样,它们无法访问构造函数被调用时存在的局部变量。

【讨论】:

    【解决方案2】:

    不幸的是,您根本无法做到您想要实现的目标,因为在 JavaScript 中创建可以访问私有变量的公共函数的唯一方法是在与私有变量相同的范围内声明这些函数,以便这些函数创建一个关闭这些,然后公开这些功能。

    您必须在牺牲使用原型的好处或牺牲强制隐私之间做出选择。一种被广泛采用的解决方案是依靠文档来识别私有属性,或者在它们前面加上 _ 这样的字符。但是,您始终可以将某些函数设为完全私有。

    var MyClass = (function () {
        function MyClass() {
            //private
            this._private = 'private';
            this.public = 'public';
    
            //call privateFunction in the context of the current instance
            privateFunction.call(this);
        }
    
        //public functions
        MyClass.prototype.publicFunction = function () {
        };
    
        //private function
        function privateFunction () {
        }
    
        return MyClass;
    
    })();
    

    【讨论】:

      【解决方案3】:

      http://jsfiddle.net/uy38G/

      这样做很有效

      function Test(){
          var hello = "org";   
      
          this.getHello = function(){
              return hello;
          }
      
          this.setHello = function(value){
              return hello = value;
          }
      }
      
      var test = new Test();
      
      console.log(test.getHello());
      test.setHello('new org');
      console.log(test.getHello());
      

      【讨论】:

      • 你的意思是像问题的第一个代码示例中 OP 已经在做的那样做?
      • 第一个例子没有改变。
      猜你喜欢
      • 2012-06-27
      • 2011-04-06
      • 2010-09-30
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      相关资源
      最近更新 更多