用JavaScript实现单例模式的最简单/最干净的方法是什么?
当前回答
class Singelton {
static #instance;
#testValue;
constructor() {
if (Singelton.#instance instanceof Singelton) {
return Singelton.#instance;
}
Singelton.#instance = this;
return Singelton.#instance;
}
get testValue() {
return this.#testValue;
}
set testValue(value) {
this.#testValue = value;
}
}
测试:
let x = new Singelton();
x.testValue = 123;
let y = new Singelton();
console.log({isSingelton: x === y, testValueFromY: y.testValue});
其他回答
最明确的答案应该是Addy Osmani所著的《学习JavaScript设计模式》一书。
var mySingleton = (function () { // Instance stores a reference to the singleton var instance; function init() { // Singleton // Private methods and variables function privateMethod(){ console.log( "I am private" ); } var privateVariable = "I'm also private"; var privateRandomNumber = Math.random(); return { // Public methods and variables publicMethod: function () { console.log( "The public can see me!" ); }, publicProperty: "I am also public", getRandomNumber: function() { return privateRandomNumber; } }; }; return { // Get the singleton instance if one exists // or create one if it doesn't getInstance: function () { if ( !instance ) { instance = init(); } return instance; } }; })();
您可以在每次新的执行中返回相同的实例-
function Singleton() {
// lazy
if (Singleton.prototype.myInstance == undefined) {
Singleton.prototype.myInstance = { description: "I am the instance"};
}
return Singleton.prototype.myInstance;
}
a = new Singleton();
b = new Singleton();
console.log(a); // { description: "I am the instance"};
console.log(b); // { description: "I am the instance"};
console.log(a==b); // true
这应该可以工作:
function Klass() {
var instance = this;
Klass = function () { return instance; }
}
关键是要理解闭包背后的重要性。因此,在闭包的帮助下,即使在内部函数内部的属性也将是私有的。
var Singleton = function () {
var instance;
function init() {
function privateMethod() {
console.log("private via closure");
}
var privateVariable = "Private Property";
var privateRandomNumber = Math.random(); // This is also private
return {
getRandomNumber: function () { // Access via getter in init call
return privateRandomNumber;
}
};
};
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
}
};
};
var singleton = (function () {
var singleton = function(){
// Do stuff
}
var instance = new singleton();
return function(){
return instance;
}
})();
一个没有getInstance方法的解决方案。
推荐文章
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 在哪里放置AutoMapper.CreateMaps?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- 在Bash中传递带有空格的字符串作为函数参数
- ES6/2015中的null安全属性访问(和条件赋值)
- 在R函数中指定可选参数的“正确”方法
- 使用Enum实现单例(Java)
- 与push()相反;
- JS字符串“+”vs concat方法