【问题标题】:How do I access private properties from function prototype in javascript module pattern?如何从 javascript 模块模式中的函数原型访问私有属性?
【发布时间】:2013-01-06 15:40:36
【问题描述】:

我一直在寻找一种使用构造函数模块模式访问私有属性的方法。我想出了一个可行的解决方案,但不确定这是最优的。

mynamespace.test = function () {
    var s = null;

    // constructor function.
    var Constr = function () {
        //this.s = null;

    };

    Constr.prototype.get = function () {
        return s;
    };

    Constr.prototype.set = function (s_arg) {
        s =  s_arg;
    };

    // return the constructor.
    return new Constr;
};


var x1 = new mynamespace.test();
var x2 = new mynamespace.test();
x1.set('x1');
alert('x1 get:' + x1.get()); // returns x1
x2.set('x2');
alert('x2 get:' + x2.get()); // returns x2
alert('x1 get: ' + x1.get()); // returns x1

【问题讨论】:

  • 这与当前的 JavaScript 一样好。但是,您不应返回“新构造函数”(即实例),而应仅返回构造函数本身 (return Constr;)。
  • 不能optimal(例如,利用 prototype 继承)隐藏在 JavaScript 中的私有成员。您可以拥有具有 prototype 继承的虚假私有成员(例如 this._imAPrivateMember),仅此而已。在您的情况下,您创建的每个 new mynamespace.test 都定义了一个新的 Contr 和一个 prototype 链。
  • 感谢您的帮助。我的意思是每次都创建一个新实例,因为我想存储在特定实例化的原型函数之间共享的私有属性。 ECMA5 是否满足了这一需求?

标签: javascript properties module prototype private


【解决方案1】:
mynamespace.Woman = function(name, age) {
    this.name = name;

    this.getAge = function() {
        // you shouldn't ask a woman's age...
        return age;
    };

    this.setAge = function(value) {
        age = value;
    };
};

var x1 = new mynamespace.Woman("Anna", 30);
x1.setAge(31);
alert(x1.name); // Anna
alert(x1.age); // undefined
alert(x1.getAge()); // 31

这与您的解决方案之间的区别在于,您的解决方案每次调用 namespace.test() 时都会生成一个新的 Consr。这是一个细微的差别,但这仍然是首选。

其中一个区别是您可以使用:

x1 instanceof mynamespace.Woman

而在您的解决方案中,x1 的类型与 x2 不同,因为它们使用不同的 Constr。

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    相关资源
    最近更新 更多