所以我对 js 还是很陌生,我想了解更高级的东西,但是我遇到了工厂模式的问题,这是基本代码:
(function () {
var objs = [];
function createObj(name) {
var thename = name;
return {
publicsaythename : function () {
console.log(thename);
}
}
}
for(var i = 0; i < 5; i++) {
var theObj = createObj("thename" + i);
theObj.publicsaythename();
objs.push(theObj);
}
for(var i = 0; i < objs.length; i++) {
theObj.publicsaythename();
}
})();
第一系列的 console.log 调用输出我所期望的:
thename0
thename1
thename2
thename3
thename4
第二系列console.logs 输出我创建的最后一个对象5次。
5 x thename4
我做错了什么吗?或者这是预期的?
如果是预期的话。您如何解决能够存储您创建的对象供以后使用的问题?
最佳答案
您只在 theObj
变量中存储了一个对象引用,因此输出符合预期。
我认为这就是您打算在第二个循环中执行的操作:
for(var i = 0; i < objs.length; i++) {
objs[i].publicsaythename();
}
所以存储对象的方式没有任何问题。我猜你只是在使用它们时犯了一个错误。 :-)
关于javascript - JS - 工厂模式在存储在内存中时覆盖私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16066844/