用私有变量创建单例的方法? [英] Ways to create a singleton with private variables?
本文介绍了用私有变量创建单例的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个单变量,其变量不能从外部直接更改。这是我当前的代码:
I'm trying to create a singleton that has variables not directly mutable from the outside. This is my current code:
var singleton = new (function () {
var asd = 1;
this.__defineGetter__("Asd", function() {
return asd;
});
})();
alert(singleton.Asd) // test
但是,似乎就像很多丑陋的代码,只是为了实现一个简单的事情。
However, it seems like alot of ugly code just to achieve a simple thing.
用这样的 private 变量创建单例的更干净的替代方法是什么?
What are some cleaner alternatives to create a singleton with such private variables?
推荐答案
我认为只有闭包才能在JavaScript中带来真正的私有变量。通常,我们使用某种命名约定来告诉变量是否为私有。
I think only closure can bring real private variable in JavaScript. Usually we use some kind of naming convention to tell if the variable is private.
var TheStaticClass;
(function () {
var a=1;
TheStaticClass.__defineGetter__("A", function() {
return a;
});
})();
alert(TheStaticClass.A) // test
这篇关于用私有变量创建单例的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文