用JavaScript实现单例模式的最简单/最干净的方法是什么?
当前回答
模块模式:“更具可读性的风格”。您可以很容易地看到哪些方法是公共的,哪些是私有的
var module = (function(_name){
/* Local Methods & Values */
var _local = {
name : _name,
flags : {
init : false
}
}
function init(){
_local.flags.init = true;
}
function imaprivatemethod(){
alert("Hi, I'm a private method");
}
/* Public Methods & variables */
var $r = {}; // This object will hold all public methods.
$r.methdo1 = function(){
console.log("method1 calls it");
}
$r.method2 = function(){
imaprivatemethod(); // Calling private method
}
$r.init = function(){
inti(); // Making 'init' public in case you want to init manually and not automatically
}
init(); // Automatically calling the init method
return $r; // Returning all public methods
})("module");
现在你可以使用公共方法,比如
module.method2 ();// ->我正在调用一个私有方法超过一个公共方法警报(“嗨,我是一个私有方法”)
http://jsfiddle.net/ncubica/xMwS9/
其他回答
剥猫皮的方法不止一种:)根据你的口味或特定需求,你可以应用任何一种建议的解决方案。我个人倾向于Christian C. Salvadó的第一个解决方案(当你不需要隐私的时候)。
因为这个问题是关于最简单和最干净的,所以这个问题是赢家。甚至:
var myInstance = {}; // Done!
这(引用自我的博客)……
var SingletonClass = new function() {
this.myFunction() {
// Do stuff
}
this.instance = 1;
}
没有太大的意义(我的博客例子也没有),因为它不需要任何私有变量,所以它几乎与:
var SingletonClass = {
myFunction: function () {
// Do stuff
},
instance: 1
}
我的意见:我有一个构造函数(CF),例如,
var A = function(arg1){
this.arg1 = arg1
};
我只需要这个CF创建的每个对象都是相同的。
var X = function(){
var instance = {};
return function(){ return instance; }
}();
Test
var x1 = new X();
var x2 = new X();
console.log(x1 === x2)
我需要几个单人间:
延迟初始化 初始参数
这就是我想到的:
createSingleton ('a', 'add', [1, 2]);
console.log(a);
function createSingleton (name, construct, args) {
window[name] = {};
window[construct].apply(window[name], args);
window[construct] = null;
}
function add (a, b) {
this.a = a;
this.b = b;
this.sum = a + b;
}
args必须是Array,所以如果你有空变量,只需要传入[] 我在函数中使用了window对象,但我本可以传入一个参数来创建自己的作用域 name和构造参数只是字符串,以便window[]工作,但有一些简单的类型检查,window.name和window.name。构造也是可能的。
如果你正在使用node.JS,那么你可以利用node.JS的缓存机制,你的单例将像这样简单:
class Singleton {
constructor() {
this.message = 'I am an instance';
}
}
module.exports = new Singleton();
请注意,我们导出的不是类Singleton,而是实例Singleton()。
Node.JS将在每次需要时缓存和重用相同的对象。
更多细节请查看:Node.JS和单例模式
let MySingleton = (function () {
var _instance
function init() {
if(!_instance) {
_instance = { $knew: 1 }
}
return _instance
}
let publicAPIs = {
getInstance: function() {
return init()
}
}
// this prevents customize the MySingleton, like MySingleton.x = 1
Object.freeze(publicAPIs)
// this prevents customize the MySingleton.getInstance(), like MySingleton.getInstance().x = 1
Object.freeze(publicAPIs.getInstance())
return publicAPIs
})();
推荐文章
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数
- 如何在JavaScript中转义单引号(')?
- Ng-repeat结束事件
- 谷歌MAP API未捕获的类型错误:无法读取属性“offsetWidth”为空
- 模糊vs聚焦-有什么真正的区别吗?
- 错误:无法找到函数…在R
- 如何使用JavaScript创建和样式一个div ?