问题描述
在 JavaScript 中实现单例模式最简单/最干净的方法是什么?
推荐答案
我认为最简单的方法是声明一个简单的对象字面量:
var myInstance = { method1: function () { // ... }, method2: function () { // ... } };
如果你想在你的单例实例上使用私有成员,你可以这样做:
var myInstance = (function() { var privateVar = ''; function privateMethod () { // ... } return { // public interface publicMethod1: function () { // all private members are accesible here }, publicMethod2: function () { } }; })();
问题描述
What is the simplest/cleanest way to implement singleton pattern in JavaScript?
推荐答案
I think the easiest way is to declare a simple object literal:
var myInstance = { method1: function () { // ... }, method2: function () { // ... } };
If you want private members on your singleton instance, you can do something like this:
var myInstance = (function() { var privateVar = ''; function privateMethod () { // ... } return { // public interface publicMethod1: function () { // all private members are accesible here }, publicMethod2: function () { } }; })();
This is has been called the module pattern, it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.