在javascript中还有其他实现单例模式的方法吗?
Is there any other way to implement Singleton Pattern in javascript?
尝试在javascript中实现一些教程中的单例模式。只是想知道是否有其他方法来实现相同的?
var singleton = (function(){
var getInstance; //private variable
var createWidget = function(){
var todayDate = new Date(); //private
var addCSS = function(){
console.log('THis is my css function');
};
var getDropDownData = function(){
console.log('This is my getDropDownData function');
};
return {
getDropDownData : getDropDownData,
addCSS: addCSS
};
};
return {
getInstance: function(){
if(!getInstance) {
getInstance = createWidget();
}
return getInstance;
}
};
})();
var obj = singleton.getInstance();
通过在onLoad上运行匿名函数并将其赋值给某个变量来实现。
您总是可以编写一个函数来抽象编写单例的样板。例如,我要这样做:
function singleton(prototype) {
var instance = null;
return {
getInstance: function () {
if (instance === null) {
var Instance = prototype.init || function () {};
Instance.prototype = prototype;
instance = new Instance;
} return instance;
}
};
}
然后你可以使用这个函数创建单例,如下所示:
var Widget = singleton({
init: function () {
var todayDate = new Date; // private
},
addCSS: function () {
console.log("This is my addCSS function.");
},
getDropDownData: function () {
console.log("This is my getDropDownData function.");
}
});
之后像平常一样使用单例:
var widget = Widget.getInstance();
希望对你有帮助。
相关文章:
- AngularJS 模式单例在服务中未更新视图
- Javascript 单例模式
- 为什么这个javascript单例方法有效
- 在单例模式中引用变量的根父级
- Javascript 文字对象和单例模式
- node.jssocket.io定时器-单例模式
- 使用单例模式维护整个应用中的数组状态
- 用于特殊单例模式的JSDoc
- 在javascript中还有其他实现单例模式的方法吗?
- 通过对象字面量的单例与模块模式的对比,代码组织的利弊
- JavaScript单例模式-差异
- 这种创建对象的方法是否只适用于单例对象?
- 在Typescript/ES6中,单例模式的正确方式是什么?
- _.bindAll()用于JavaScript单例方法
- 如何保存javascript "this"单例模式中的上下文
- 下面这个单例模式有什么问题吗?
- 具有异步初始化的单例模式
- JavaScript单例类型错误:为什么严格模式会标记这个
- 用这种方式实现Javascript单例模式有什么问题吗?
- 用私有变量创建单例的方法