代码之家  ›  专栏  ›  技术社区  ›  mrshl

Javascript作用域:匿名函数中的访问类字段

  •  0
  • mrshl  · 技术社区  · 8 年前

    我的(Javascript)代码中遇到了一个有趣的问题,我认为这与范围有关如果是这样的话,我想更好地理解JS中的范围。

    我怀疑这是否相关,但我也在与React和D3合作。

    我的代码要点如下:

    // 1
    
    export default class C extends Component {
        // 2
    
        componentDidUpdate() {
            // 3
    
            ...
            var node = svg.append('svg')
                .append('svg:image')
                .attr('xlink:href', function(d) {
                    // 4
    
                    return dict['foo'];
                });
        }
    }
    

    我试图在匿名函数中使用外部对象的内容。

        dict = {
            foo: 'bar.svg'
        };
    

    到目前为止,我发现如果我在位置上声明上述对象 三 或 四 ,代码执行得很好但是,如果我将对象声明移到方法之外( 二 ),或者完全不在课堂上( 一 ),我得到一个错误: dict is not defined .

    如果位置1和位置2使它们无法在匿名函数中使用呢?

    2 回复  |  直到 8 年前
        1
  •  1
  •   RustyDev    8 年前

    我相信你应该能够使用箭头功能。

    export default class C extends Component {
        componentDidUpdate() {
            ...
            var node = svg.append('svg')
                .append('svg:image')
                .attr('xlink:href', (d) => this.dict['foo']);
        }
    }
        2
  •  -2
  •   Shahriat Hossain    8 年前

    javascript中有两个作用域本地范围和全局范围如果你有类似的功能

    TestFunc() {
    // here variable 'a' local variable in this function
    // and you can't access 'a' outside of this function
     var a = 'test';
    }
    
    but if you have a class like
    class TestClass {
     // here 'b' is a global variable of this class
     // and it can be accessed from any of the method of this class using 'this' keyword
     b: string;
    
     // example of method
     TestGFunction() {
     // here 'b' is a global variable of class 'TestClass'
      this.b = 'test3';
    }
    }
    

    希望它能帮助您理解javascript中本地和全局范围的概念。

    推荐文章