gpt4 book ai didi

javascript - 模块模式真的必须是单例模式吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:46:23 29 4
gpt4 key购买 nike

模块模式被大多数人描述为:

var module = (function() {
// private fields
var a, b, c;

// private functions
function myFunction() {}

// public data (where you expose to outside)
return {
publicFunc: function() {}
};
})();

但是上面的代码创建了模块的单个实例。真的必须是单例吗?

下面的代码还是模块模式吗?

function module() {

// same code

return {
publicFunc: function() {}
};
}

最佳答案

是的,模块模式返回一个单例,但这并不是一个实际的限制。您可以使用模块模式返回单例工厂函数,然后多次调用该工厂函数。

var point = (function() {
// Add private code here to make use of module pattern.
// If you don't have anything to keep private, then
// module pattern is overkill, as noted in the comments
return function(x,y) {
return {
x : x,
y: y
}
}
})();

var point1 = point(0,0);
var point2 = point(3,4);

在不使用工厂函数的情况下,您还可以将模块模式放入一个循环中并多次执行(不推荐这样做,因为它非常低效):

var points = [];
for (var i=0; i<4; i++){
points[i] = (function module() {
// same code
return {
publicFunc: function() {}
};
})();
}

更新:根据下面@North 和@Bergi 的反馈,在第一个示例中添加了评论

关于javascript - 模块模式真的必须是单例模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24861176/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com