考虑以下简单脚本:
var sourcePath = 'src';
function setPath(path){
sourcePath = path || sourcePath;
return sourcePath;
}
console.log('sourcePath is ' + setPath('somepath') + ' from setPath.js calling the function');
console.log('sourcePath is ' + sourcePath + ' from setPath.js sourcePath vaue ');
exports.getCustomContextPath = setPath;
exports.sourcePath = sourcePath;
运行此脚本时,运行此脚本的输出符合预期:
sourcePath is somepath from setPath.js calling the function
sourcePath is somepath from setPath.js sourcePath value
如果我在测试器文件中导入相同的文件并像这样使用它:
const pathSetter = require('./setPath');
var test = pathSetter.getCustomContextPath('./temp/test');
console.log('the path set from test.js ' + test + " by calling getCustomContextPath function with '.temp/test'" )
console.log('the path set from test.js ' + pathSetter.sourcePath + " this is the sourcePath value after calling with '.temp/tr'" )
var test2 = pathSetter.getCustomContextPath();
console.log('the path set from test.js' + test2 + " by calling getCustomContextPath function with no parameter " )
console.log('the path set from test.js ' + pathSetter.sourcePath + " this is the sourcePath value after calling with no parameter")
我希望在调用函数时sourcePath
变量的值会更改setPath
但正如您在下面看到的,在打印出sourcePath
的值时,它仍然设置为其默认值somePath
。下面是运行测试脚本的输出:
sourcePath is somepath from setPath.js calling the function
sourcePath is somepath from setPath.js sourcePath value
the path set from test.js ./temp/test by calling getCustomContextPath function with '.temp/test'
the path set from test.js somepath this is the sourcePath value after calling with '.temp/tr'
the path set from test.js./temp/test by calling getCustomContextPath function with no parameters
the path set from test.js somepath this is the sourcePath value after calling with no parameters
谁能告诉我为什么在我期望脚本函数更改它之后没有更改sourcePath
的值,而只是当我从测试文件目录访问它而不是函数调用返回它时?
当你做exports.sourcePath = sourcePath;
时,你是在做一个简单的分配。
var sourcePath
不是指针。因此,它在导出时初始化为somepath
并且永远不会更改。
如果要检索良好的 sourcePath 值,可以按exports.sourcePath = () => sourcePath;
exports.sourcePath = sourcePath;
这里sourcePath不是通过引用设置的。一旦你在export.sourcePath中导出了一个值,即使你改变全局变量">sourcePath"的值,它也不会改变;
考虑它就像你写的那样
export.sourcePath = "somepath";
现在它将如何改变,现在没有办法改变它。
您的困惑是,您将其设置为同一文件一次,但是在这种情况下,在执行exports.sourcePath之前,您将其值更改为"somePath"。
现在您可以尝试的是,尝试从第一个文件中删除这两行
console.log('sourcePath is ' + setPath('somepath') + ' from setPath.js calling the function');
console.log('sourcePath is ' + sourcePath + ' from setPath.js sourcePath vaue ');
然后尝试在不同的文件中打印其值。它将始终打印"src"。