Node.js脚本私有变量值不会被内部函数更改

时间:2017-08-24 16:04:14

标签: javascript node.js

考虑以下简单脚本:

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的值没有改变,但只有当我的目录从测试文件中访问它时,与函数调用何时返回它相反?

2 个答案:

答案 0 :(得分:0)

当你做exports.sourcePath = sourcePath;时,你正在做一个简单的分配。

var sourcePath不是指针。因此它在导出时被初始化为somepath并且永远不会改变。

如果要检索良好的sourcePath值,可以执行exports.sourcePath = () => sourcePath;

答案 1 :(得分:0)

exports.sourcePath = sourcePath;

此处 sourcePath 未按引用设置。在 exports.sourcePath 中导出值后,即使更改全局变量“ sourcePath ”的值,它也不会更改;

认为就像你写的那样

exports.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”。