javascript jquery更改函数内的全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27650979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:47:33  来源:igfitidea点击:

jquery change global variable inside function

javascriptjquery

提问by Wizard

var variable = "before";

change();

alert(variable);

function change(){

variable = "after";

}

Does in possible to change global variable inside function without return ? I need after call function changehave output "after"

是否可以在不返回的情况下更改函数内部的全局变量?我需要调用函数change输出“after”

回答by Drazzah

Yes, it is possible, but remember to NOT put the varkeyword in front of it inside the function.

是的,这是可能的,但请记住不要将var关键字放在函数内部的前面。

ERORR - DOES NOT WORK:

错误 - 不起作用:

var variable = "before";

change();

alert(variable);

function change() {

  var variable = "after";

}

WORKS:

作品:

var variable = "before";

change();

alert(variable);

function change() {

  variable = "after";

}

回答by Dom

You should avoid declaring global variables since they add themselves as properties to the window. However, to answer your question, yes you can change global variables by setting either changing variableor window.variable.

您应该避免声明全局变量,因为它们将自己作为属性添加到window. 但是,要回答您的问题,是的,您可以通过设置更改variable或来更改全局变量window.variable

Example: http://jsbin.com/xujenimiwe/3/edit?js,console,output

示例:http: //jsbin.com/xujenimiwe/3/edit?js,console,output

var variable = "before"; // will add property to window --  window.variable

console.log(variable);

change();

console.log(window.variable);

function change(){

 variable = "after"; // can also use window.variable = "after"
}

Please let me know if you have any questions!

请让我知道,如果你有任何问题!