如何在javascript中访问当前范围之外的变量? [英] How can I access variables outside of current scope in javascript?

查看:113
本文介绍了如何在javascript中访问当前范围之外的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中编写一个应用程序,无法弄清楚如何访问在我的函数中声明的变量,在这个jQuery解析。内部我可以访问全局变量,但我真的不想为这些值创建全局变量。

I'm writing an application in javascript and cannot figure it out how to access the variables declared in my function, inside this jquery parse. Inside I can access global variables, but I don't really want to create global vars for these values.

基本上我想从xml文档中提取文件名 simulationFiles 变量。我检查节点属性是否等于 simName ,并提取xml元素内的两个字符串,这部分我认为它是工作。

Basically I want to extract file names from an xml document in the simulationFiles variable. I check if the node attribute is equal with the simName and extract the two strings inside the xml elements, that part I think it's working.

如何提取这些xml元素并将它们附加到局部变量?

How can I extract those xml elements and append them to local variables?

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();
       }
    });
}   


推荐答案

中的函数不一样 each()回调(其中,它是迭代中的当前元素)。要在回调中访问外部函数的范围,我们需要能够使用另一个名称来引用它,您可以在外部范围中定义它:

The this in the CsvReader function is not the same this in the each() callback (where instead it is the current element in the iteration). To access the scope of the outer function within the callback, we need to be able to reference it by another name, which you can define in the outer scope:

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();
       }
    });
}

这篇关于如何在javascript中访问当前范围之外的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆