簡體   English   中英

內部函數不會更改Node.js腳本私有變量的值

[英]Node.js script private variable value is not changed by the internal function

考慮以下簡單腳本:

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")

我希望在調用setPath函數時可以更改sourcePath變量的值,但是如下所示,當打印出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並非通過引用設置。 一旦在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”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM