gpt4 book ai didi

javascript - 如何从 javascript 模块模式中的函数原型(prototype)访问私有(private)属性?

转载 作者:行者123 更新时间:2023-11-30 06:36:22 24 4
gpt4 key购买 nike

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

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

最佳答案

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。这是一个细微的差别,但这仍然是首选。

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

x1 instanceof mynamespace.Woman

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

关于javascript - 如何从 javascript 模块模式中的函数原型(prototype)访问私有(private)属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14183694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com