我正在学习 JavaScript 中的设计模式,并且正在学习 Singleton
设计模式。这是代码:
var SingletonTester = (function () {
// options: an object containing configuration options for the singleton
// e.g var options = { name: 'test', pointX: 5};
function Singleton(options) {
// set options to the options supplied or an empty object if none provided.
options = options || {};
//set the name parameter
this.name = 'SingletonTester';
//set the value of pointX
this.pointX = options.pointX || 6;
//set the value of pointY
this.pointY = options.pointY || 10;
}
// this is our instance holder
var instance;
// this is an emulation of static variables and methods
var _static = {
name: 'SingletonTester',
// This is a method for getting an instance
// It returns a singleton instance of a singleton object
getInstance: function (options) {
if (instance === undefined) {
instance = new Singleton(options);
}
return instance;
}
};
return _static;
})();
var singletonTest = SingletonTester.getInstance({
pointX: 5
});
var singletonTest1 = SingletonTester.getInstance({
pointX: 15
});
console.log(singletonTest.pointX); // outputs 5
console.log(singletonTest1.pointX); // outputs 5
我不明白为什么变量 instance
在启动 singletonTest1
时会获得一些值。
最佳答案
当模块 SingletonTester
创建后,又称为:
var SingletonTester = (function () {
// ... stuff in here
var instance;
})(); // <--- here
最后一行是函数应用程序 ();
。申请后SingletonTester
模块包含其所有封闭状态。
自 instance
是由 SingletonTester
关闭的属性(property)闭包,实例在 SingletonTester
的整个存在期间活着 .
旁注:单例模式主要是创建线程安全的静态实例以跨进程共享。由于JavaScript是单线程的,这显然不是问题。您可以让事情变得简单,只使用全局变量。
关于javascript - JavaScript 中的单例实例范围困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34899590/