admin管理员组文章数量:1242824
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 change
have output "after"
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 change
have output "after"
- It is possible, but why would you use globals to begin with? Why can't the function take one argument? – elclanrs Commented Dec 25, 2014 at 21:49
- I want set variable globally from ajax response – Wizard Commented Dec 25, 2014 at 21:50
- You may want to check this question, because that's seems like a pretty mon mistake. – elclanrs Commented Dec 25, 2014 at 21:51
- 2 Short answer is yes. Long answer is you should read this, and this, to get to know all you need about scopes in JavaScript. – Alexander Art Commented Dec 25, 2014 at 21:54
- 2 If it's ajax, you should say so in the question, as Asynchronous Javascript And XML is ... wait for it... asynchronous, and setting global variables is not the solution, as others above have noted. – adeneo Commented Dec 25, 2014 at 22:00
2 Answers
Reset to default 9Yes, it is possible, but remember to NOT put the var
keyword in front of it inside the function.
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";
}
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 variable
or window.variable
.
Example: http://jsbin./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!
本文标签: javascriptjquery change global variable inside functionStack Overflow
版权声明:本文标题:javascript - jquery change global variable inside function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740070700a2223043.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论