最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery change global variable inside function - Stack Overflow

programmeradmin3浏览0评论
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"

Share Improve this question edited Dec 25, 2014 at 22:09 Alexander Art 1,5892 gold badges24 silver badges51 bronze badges asked Dec 25, 2014 at 21:47 WizardWizard 11.3k38 gold badges99 silver badges167 bronze badges 6
  • 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
 |  Show 1 more ment

2 Answers 2

Reset to default 9

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./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!

发布评论

评论列表(0)

  1. 暂无评论