【问题标题】:Javascript Scope: Access class field within anonymous functionJavascript Scope:匿名函数中的访问类字段
【发布时间】:2018-07-24 01:16:32
【问题描述】:

我在我的 (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'
    };

到目前为止,我发现如果我在 34 位置声明上述对象,代码执行得很好。但是,如果我将对象声明移到方法之外 (2) 或完全移到类之外 (1),我会收到错误:dict is not defined

位置 1 和 2 导致它们无法在匿名函数中使用怎么办?

【问题讨论】:

  • return this.dict['foo'];
  • AFAIK 你还不能在类声明中声明类变量。 This answer 提到使用 babel(你会做出反应)可能支持这一点,但我不知道它是如何被转译的。添加类变量的 ECMAScript 提议可能是this one

标签: javascript reactjs d3.js scope anonymous-function


【解决方案1】:

我相信你应该可以使用箭头函数。

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

【讨论】:

【解决方案2】:

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中本地和全局范围的概念。

【讨论】:

  • 如果您尝试编译TestClass,是否会在控制台上收到任何错误消息?
  • 我上面的代码只是作为理解概念的示例。
  • 但这不起作用。您不能在类声明中定义变量。
  • 是的,我知道,不过更新了代码并感谢您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-26
  • 1970-01-01
  • 1970-01-01
  • 2014-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多