【发布时间】:2022-02-08 07:29:58
【问题描述】:
function creatPrintNumFunction()
{
var num= 12;
return function printNum()
{
console.log(num);
}
}
var printer = creatPrintNumFunction();
printer.num =13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();
那么我怎样才能让这段代码打印 13 而不是 12最重要的是不更改 createPrintNumFunction() 的任何代码。
有关我真正需要使用该理论的更多背景信息。我在 node.js 中使用了一个我不想更改的外部模块 express-sessions。有一个“存储”变量,所有会话都存储在其中,我需要访问唯一的问题是它是在函数中创建的。还有另一种方法可以访问它,但它不是很方便
【问题讨论】:
-
就目前而言,您的代码不使用
num局部变量;它打印未定义的store全局变量。我怀疑您在发布问题时过度简化了代码。 -
对不起,我编辑修复这是一个分散注意力的错误
-
使用您显示的代码,无法从
creatPrintNumFunction函数外部修改num局部变量。 -
是的,现在我知道我想要做的事情是不可能的,谢谢
标签: javascript node.js