简体   繁体   中英

jquery change global variable inside function

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"

Yes, 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.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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM