![](/img/trans.png)
[英]Javascript: How can I access a function-scoped variable within a do while loop?
[英]In Javascript, how can I reference a function-scoped variable from a function called within that function but defined elsewhere?
我有一个类似这样的Javascript函数,它在无法更改的地方定义:
foo.customSave = [];
foo.save = function() {
var saveString = 'initial value';
// stuff about saveString here
for (i in foo.customSave) { foo.customSave[i](); }
// more stuff about saveString here, including actually saving it
};
然后我有自己的代码,如下所示:
bar.init = function() {
// other init stuff here
foo.customSave.push(function() {
saveString += 'something meaningful here';
});
// more other init stuff here
};
bar.init()
被调用在适当的时间(这就是说,前foo.save()
被调用)。 问题似乎是当我尝试向其中添加'something meaningful here'
时未定义saveString
(将console.log
调用放在'something meaningful here'
即可确认这一点)。
我的customSave
函数可以以任何方式访问该字符串,还是卡住了?
鉴于您无法修改与foo.save
关联的函数,因此无法修改saveString
变量。 这是因为saveString
是局部变量,其作用域是与foo.save
关联的foo.save
。 结果,您可以调用该函数,但是它基本上就像一个黑匣子,在其中您无法访问在其中定义的变量(实际上,如果不查看源代码,您甚至不会知道saveString
变量存在)。
在与相关的功能bar.init
,你要创建一个新的函数对象每次bar.init
被调用,它推到一个数组。 并且因为您没有使用var
来声明saveString
变量,所以JavaScript会尝试在要推送到数组的函数中找到saveString
变量。 由于在此处找不到声明,因此JavaScript将继续在下一个外部范围中bar.init
与bar.init
关联的函数中的bar.init
。 由于也无法在其中找到JavaScript,因此JavaScript会最后尝试在全局范围内找到它(也不会在其中获得成功)。
希望能有所帮助,但总而言之,不能修改foo.save
,您会陷入困境。
如何将saveString
添加为foo
的属性?
像这样:
foo.customSave = [];
foo.saveString = '';
foo.save = function() {
foo.saveString = 'initial value';
// stuff about saveString here
for (i in foo.customSave) { foo.customSave[i](); }
// more stuff about saveString here, including actually saving it
};
然后:
bar.init = function() {
// other init stuff here
foo.customSave.push(function() {
foo.saveString += 'something meaningful here';
});
// more other init stuff here
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.