如何在javascript中访问当前范围之外的变量?
问题描述:
我正在写一个应用程序在JavaScript中,无法弄清楚如何访问我的函数中声明的变量,在这个jQuery解析。在里面我可以访问全局变量,但我并不想为这些值创建全局变量。如何在javascript中访问当前范围之外的变量?
基本上我想从simulationFiles
变量的xml文档中提取文件名。我检查节点属性是否与simName
相同,并提取xml元素中的两个字符串,我认为这部分工作。
如何提取这些XML元素并将它们附加到局部变量?
function CsvReader(simName) {
this.initFileName = "somepath";
this.eventsFileName = "somepath";
$(simulationFiles).find('simulation').each(function() {
if ($(this).attr("name") == simName) {
initFileName += $(this).find("init").text();
eventsFileName += $(this).find("events").text();
}
});
}
答
在CsvReader
功能this
不在each()
回调(其中相反,它是在迭代当前元素)相同this
。回调中访问外部函数的范围,我们需要的是能够通过另外一个名字,您可以在外部范围定义引用它:
function CsvReader(simName) {
this.initFileName = "somepath";
this.eventsFileName = "somepath";
var self = this; // reference to this in current scope
$(simulationFiles).find('simulation').each(function() {
if ($(this).attr("name") == simName) {
// access the variables using self instead of this
self.initFileName += $(this).find("init").text();
self.eventsFileName += $(this).find("events").text();
}
});
}
答
我做了一个working demo(我改变了它使用类,所以它可以使用HTML)。
function CsvReader(simName) {
this.initFileName = "somepath";
this.eventsFileName = "somepath";
var context = this;
$(simulationFiles).find('simulation').each(function() {
if ($(this).attr("name") == simName) {
context.initFileName += $(this).find("init").text();
context.eventsFileName += $(this).find("events").text();
}
});
}
+0
这种方法工作得很好,thx!对不起,但调试器的小姐给我带来了一点教导它不起作用。 – sekmet64 2010-05-02 20:43:18
Thx为快速回答,但不幸的是,这是行不通的。其实我以前也尝试过,但在未命名的函数中,$ self被报告为未由萤火虫定义。 – sekmet64 2010-05-02 20:27:38
它的工作原理就是这样!对不起,当我将这个保存到一个变量后,我有一个不同的错误后,此函数调用,当我调试调试器显示我$ self.initFileName是内部未定义,但实际上它工作,并且我得到了结果。 非常感谢! – sekmet64 2010-05-02 20:37:26
你的'this.initFileName'和'this.eventsFileName'应该是你的函数本地还是整个页面? Nm ...几秒后看到你的帖子。很高兴它的工作! – 2010-05-02 20:37:32