简体   繁体   English

在javascript中的文字函数中更改变量的值

[英]change the value of a variable within a literal function in javascript

I'd like to know how to get this result: 我想知道如何得到这个结果:

function() {
   var myVar = "";
   function () {
      myVar += "This is ";
   }
   myVar = "my string";
   alert(myVar); //would like it to display: This is my string
   // only displays: my string
}

You A. have to call a function for it to execute and B. must reorganize you string a bit 您A.必须调用一个函数才能执行,并且B.必须稍微重组一下字符串

function() {
   var myVar = "";
   function update() {
      myVar = "This is " + myVar;
   }
   myVar = "my string";
   update();
   alert(myVar); //would like it to display: This is my string
   // only displays: my string
}

You have to call the function. 您必须调用该函数。

var myVar = "";
function someFunction() { // Give it a name
   myVar += "This is ";
}
myVar = "my string";
someFunction(); // and call it
alert(myVar); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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