英文:
Javascript Module Pattern, get modified private variable as public
问题
Sure, here's the translated code part:
你能告诉我如何将修改后的私有变量变为公共的吗?
let Module = (function(){
let privateObject = {};
function init(){
privateObject = {test:true}
}
return {
init,
privateObject
}
})();
Module.init();
console.log(Module.privateObject);
我尝试过类似这样的方法,但我相当确定我漏掉了某些东西。
let Module = (function(){
function init(){
publicObject.privateObject.test = true;
}
let publicObject = {
privateObject: {},
init
}
return publicObject;
})();
Module.init();
console.log(Module.privateObject); // 输出 {test: true}
注意:这里的翻译只包括代码部分,不包括问题或其他内容。
英文:
Can you tell me how to get modified private variable as public?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let Module = (function(){
let privateObject = {};
function init(){
privateObject = {test:true}
}
return {
init,
privateObject
}
})();
Module.init();
console.log(Module.privateObject);
<!-- end snippet -->
I've tried something like this but I am pretty sure that I'm missing something.
let Module = (function(){
function init(){
publicObject.privateObject.test = true;
}
let publicObject = {
privateObject: {},
init
}
return publicObject;
})();
Module.init();
console.log(Module.privateObject); // gives {test: true}
答案1
得分: 1
谢谢您的评论。
我已经理解了为什么在赋新值之后
privateObject = {test:true}
Module.privateObject返回了一个空对象,因为Module.privateObject保留了对privateObject先前值的引用。感谢@jabaa
作为问题的解决方案,以下代码完美运行
let Module = (function(){
let privateObject = {};
function init(){
privateObject = {test:true}
}
function getPrivate(){
return privateObject;
}
return {
init,
getPrivate
}
})();
Module.init();
console.log(Module.getPrivate());
英文:
Thank you for your comments.
I already understand why with a new assignment of value
privateObject = {test:true}
Module.privateObject returned an empty object because Module.privateObject kept a reference to the previous value of privateObject. Thanks @jabaa
As a solution to the problem for the posterity, the following code works like a charm
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let Module = (function(){
let privateObject = {};
function init(){
privateObject = {test:true}
}
function getPrivate(){
return privateObject;
}
return {
init,
getPrivate
}
})();
Module.init();
console.log(Module.getPrivate());
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论