带Browserify / CommonJS的单例模式 [英] Singleton pattern with Browserify/CommonJS
问题描述
尝试使用Browserify在CommonJS模块中实现单例模式。到目前为止:
Trying to implement the singleton pattern within CommonJS modules, using Browserify. So far:
// foo.js
// foo.js
var instance = null;
var Foo = function(){
if(instance){
return instance;
}
this.num = 0;
return instance = new Foo();
}
Foo.prototype.adder = function(){
this.num++;
};
module.exports = Foo();
// main.js
// main.js
var foo = require('./foo.js');
console.log(foo.num); // should be 0
foo.adder(); // should be 1
var bar = require('./foo.js');
console.log(bar.num); // like to think it'd be 1, not 0
第一个问题是我得到一个<当我在浏览器中加载生成的JS文件时,超出了code>超出最大调用堆栈数的错误,但是第二,我是否正确地解决了这个问题?
First problem is that I get a maximum call stack exceeded
error when I load the built JS file in the browser, but secondly, am I approaching this correctly? Is this possible?
推荐答案
第一个问题是我得到最大调用堆栈超出错误
First problem is that I get a maximum call stack exceeded error
好吧,这来自于您的 Foo
函数递归调用新的Foo
…
Well, that comes from your Foo
function recursively calling new Foo
…
但是第二,我是否正确地解决了这个问题?
but secondly, am I approaching this correctly?
否。对于单例来说,您不需要带有构造函数和原型的类-永远只有一个实例。只需创建一个对象,最简单的方法就是使用文字,然后返回该对象:
No. For singletons, you don't need a "class" with a constructor and a prototype - there will only ever be one instance. Simply create one object, most easily with a literal, and return that:
module.exports = {
num: 0,
adder: function(){
this.num++;
}
};
这篇关于带Browserify / CommonJS的单例模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!