[英]Why won't my global variable update after this function is called in Node.js?
My global variable isn't changing after the function is called in Node.js when I run the application in Sublime Text 3. When I run it in bash, it changes as expected.当我在 Sublime Text 3 中运行应用程序时,在 Node.js 中调用该函数后,我的全局变量没有改变。当我在 bash 中运行它时,它按预期改变。 When I replace "global.firstname = 'David'" with "window.firstname = 'David'" and run it in chrome's console, it changes as expected.
当我用“window.firstname = 'David'”替换“global.firstname = 'David'”并在chrome的控制台中运行它时,它会按预期改变。
var firstname = 'Simon';
var addSurname = function(){
var firstname = 'Gene';
var surname = 'Holmes';
var fullname = firstname + ' ' + surname;
global.firstname = 'David';
console.log(fullname);
};
addSurname();
console.log(firstname);
// Gene Holmes
// Simon
Ultimately, I want it to output最终,我希望它输出
// Gene Holmes
// David
Why isn't the "global.firstname='David'" statement updating my global variable with the Node.js build in Sublime Text 3?为什么“global.firstname='David'”语句不使用 Sublime Text 3 中的 Node.js 构建更新我的全局变量?
To use a global var in a function you just need to define it as global with var
keyword then use the same var name after the alteration of this var inside a function it is saved back in global var.要在函数中使用全局变量,您只需要使用
var
关键字将其定义为全局变量,然后在函数内部更改此变量后使用相同的变量名称,它将保存回全局变量中。 So you don't need the use of global.
所以你不需要使用
global.
or something like this.或类似的东西。
var firstname = 'Simon';
var addSurname = function(){
var firstnameTmp = 'Gene';
var surname = 'Holmes';
var fullname = firstnameTmp + ' ' + surname;
firstname = 'David';
console.log(fullname);
};
addSurname();
console.log(firstname);// Will output David.
Why use 2 variables with the same name?为什么要使用 2 个同名的变量?
var firstname = 'Simon'; var addSurname = function(){ var firstname2 = 'Gene'; var surname = 'Holmes'; var fullname = firstname2 + ' ' + surname; firstname = 'David'; console.log(fullname); }; addSurname(); console.log(firstname);
var firstname = 'Simon'; var addSurname = function(){ var firstname2 = 'Gene'; var surname = 'Holmes'; var fullname = firstname2 + ' ' + surname; firstname = 'David'; console.log(fullname); }; addSurname(); console.log(firstname);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.