gpt4 book ai didi

javascript - 执行 NodeJS 模块并注入(inject)特定变量

转载 作者:行者123 更新时间:2023-12-03 11:12:48 24 4
gpt4 key购买 nike

我有一个如下所示的模块

'use strict';

var val = GlobalVariable.someMethod();

...
...

module.exports = myExportedClass;

我用 require('./myModule'); 调用它。但想知道 GlobalVariable 是否可以动态注入(inject)。

我已经尝试过这个方法,尽管我知道这不起作用:)

(function(GlobalVariable) {
require('./myModule');
})(SomeOtherGlobalVariable);

所以它没有,因为模块将在不同的范围内执行。有没有其他方法可以在使用 require 时传递我自己的 GlobalVariable 版本。

最佳答案

是的,可以注入(inject)。执行如下操作:

module.exports = function(injectedObject) {
return {
doSomething: function() {
return injectedObject.something();
}
}
};

关于javascript - 执行 NodeJS 模块并注入(inject)特定变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27491195/

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