gpt4 book ai didi

javascript - 将 NodeJS 模块范围变量作为对象访问

转载 作者:数据小太阳 更新时间:2023-10-29 04:47:29 26 4
gpt4 key购买 nike

我可以访问 Node 全局变量作为 GLOBAL 对象的属性。

我可以用类似的方式访问模块作用域变量吗?

例如

var fns_x = function(){/*...*/};
var fns_y = function(){/*...*/};

function aFn(param){
/* moduleScope = something that allows me to access module scope variables */
if(moduleScope['fns_' + param]){
moduleScope['fns_' + param]();
}
}

/*...*/
module.exports = /*...*/

或者最好将那些变量包装在对象中?例如

var fns = {
x: x = function(){/*...*/},
y: x = function(){/*...*/}
}

function aFn(param){
if(fns[param]){
fns[param]();
}
}

/*...*/
module.exports = /*...*/

最佳答案

简短的回答是

尽管在 ECMAScript 规范中变量声明在模块的环境记录设置中可用,但指定不应以编程方式访问它。

It is impossible for an ECMAScript program to directly access or manipulate such values [spec]

一种解决方法是维护一个私有(private)变量作为函数的容器并公开一个查找函数。

var registry = {
x: function () {},
y: function () {},
};


module.exports = function (prop) {
return registry[prop];
};

请注意模块代码的静态分析以这种方式丢失。

您也可以绑定(bind)到全局环境,但您冒着覆盖模块全局范围中设置的重要变量的风险。

var that = this;

that.x = function () {};
that.y = function () {};

module.exports = function (prop) {
return that[prop];
};

关于javascript - 将 NodeJS 模块范围变量作为对象访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36837751/

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