我正在尝试在另一个文件中使用 require
导入文件。如何设置导入文件的变量。
假设“sample.js”
var a = '';
var b = '';
export.funcA = function(){
}
export.funcB = function(){
}
export.funcC = function(){
//somewhere I am using a & b variable with dynamic values that need to be set run time.
}
//script.js
var sample = require('sample.js');
//Now before using function `funcC` I want to dynamically set values of variable a & b.
so I can easily use `sample.funcC()`;
//我不想使用参数传递它。因为我已经将第三个分配给 funcC 所以我无法设置参数。
最佳答案
您可以导出对象:
// sample.js
module.exports = {
a: '',
b: '',
funcA: function funcA() {
},
funcB: function funcB() {
},
funcC: function funcC() {
return this.a + this.c;
}
};
// script.js
var sample = require('sample.js');
sample.a = 'foo';
sample.b = 'bar';
sample.funcC(); // => 'foobar';
关于javascript - 如果我导出模块,如何在模块中分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39923042/