如何在闭包中访问字符串
How to access String in Closure
通过触发 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;
}
}})();
我不知道。但是这段代码在这里工作正常。
它打印
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());
通过触发 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;
}
}})();
我不知道。但是这段代码在这里工作正常。 它打印
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());