JavaScript 中的单例实例范围混淆
Singleton instance scope confusion in JavaScript
我正在学习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
闭包封闭的属性,因此实例对于SingletonTester
的整个存在都是活动的。
旁注:单例模式主要是关于创建线程安全的静态实例,以便在进程之间共享。 由于JavaScript是单线程的,这显然不是问题。 相反,您可以保持简单,只使用全局变量。
相关文章:
- ES6构造函数返回基类的实例
- 正在全局范围中查找JavaScript函数
- 如何通过数组更新角度子范围
- KnockoutJS-组件-多个实例
- 为什么无法在TypeScript中导出类实例
- 如何使用ngrepeat和双向绑定获得指令的隔离范围
- 如何在GoogleWeb工具包(GWT)中从JSNI调用接口(实例化)
- fluxxor向一个flux实例添加一组以上的操作
- 使用jQuery获取Dropzone实例/对象
- HTML范围:动态设置值属性
- "实例范围”;TypeScript类的getter/setter
- 使用ng repeat添加多个视图实例时的范围界定问题
- 使用 jQuery 创建两个日期选取器日期范围实例
- 访问模板的实例范围并注入数据
- JavaScript 中的单例实例范围混淆
- 从构造函数实例化的类范围对象
- 同一角度指令的多个实例混淆了范围变量
- 是一个只有一个实例的类,如果它没有'没有全球范围
- 此特定实例中的javascript变量范围
- 使用日期时间选取器的多个实例来处理日期之间的范围