2

コンストラクタ モジュール パターンを使用してプライベート プロパティにアクセスする方法を探していました。機能するソリューションを思いつきましたが、これが最適かどうかはわかりません。

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
4

1 に答える 1

0
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() を呼び出すたびに、ソリューションが新しい Constr を生成することです。微妙な違いですが、それでもこれは好まれます。

違いの 1 つは、以下を使用できることです。

x1 instanceof mynamespace.Woman

あなたのソリューションでは、異なるConstrを使用するため、x1のタイプはx2とは異なります。

于 2013-01-06T16:15:47.793 に答える