JavaScript:原型函数中的私有变量

JavaScript: Private variables in prototype function

本文关键字:变量 原型 函数 JavaScript      更新时间:2023-09-26

我使用原型函数是因为当"类"被多次实例化时,它们应该具有更好的性能。此外,并不是所有的变量都应该是外部可访问的,所以它们是通过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());

与原型对象关联的函数与任何其他函数具有完全相同的对象访问权限。此外,与其他函数一样,它们对构造函数调用时存在的局部变量没有访问权限。

不幸的是,您根本无法实现您想要实现的目标,因为在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;
})();

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());