如何在Closure中访问String

时间:2015-04-28 16:25:25

标签: javascript jquery jquery-mobile closures concat

通过触发xyEvent我想连接一个字符串。但是myClosure()总是空的。为什么?谢谢你的帮助。

first.js:

$(document).ready(function () { 

$("#...").on("tap", function () {
        myClosure(new Item());
    });
...
}

second.js

var string;

xyEvent {   
        string = "hello" + myClosure();  // here is the problem
});

var myClosure = (function () {
   var anyString = "";

   return function (item) {
      if(item != null){
        anyString = anyString.concat(item.name);
        consloge.log(anyString);   // perfect at this point
      }
      else{
         return anyString;
    }
}})();

1 个答案:

答案 0 :(得分:0)

我不知道。但是这里的代码运行正常。 它打印

a
ab
abc
result = abc

var myClosure = (function () {
   var anyString = "";

   return function (item) {
      if(item != null){
        anyString = anyString.concat(item.name);
        console.log(anyString);   // perfect at this point
      }
      else{
         return anyString;
    }
}})();

myClosure({name: "a"});
myClosure({name: "b"});
myClosure({name: "c"});

console.log("result = " + myClosure());