Javascript 范围:在匿名函数中访问 class 字段
Javascript Scope: Access class field within anonymous function
我 运行 在我的 (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'
};
到目前为止,我发现如果我在 3 或 4 位置声明上述对象,代码执行得很好。但是,如果我将对象声明移到方法之外 (2),或者完全移到 class 之外 (1),我会得到一个错误:dict is not defined
。
位置 1 和 2 会怎样导致它们无法在匿名函数中使用?
我相信你应该能够使用箭头函数。
export default class C extends Component {
componentDidUpdate() {
...
var node = svg.append('svg')
.append('svg:image')
.attr('xlink:href', (d) => this.dict['foo']);
}
}
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 中局部和全局作用域的概念。
我 运行 在我的 (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'
};
到目前为止,我发现如果我在 3 或 4 位置声明上述对象,代码执行得很好。但是,如果我将对象声明移到方法之外 (2),或者完全移到 class 之外 (1),我会得到一个错误:dict is not defined
。
位置 1 和 2 会怎样导致它们无法在匿名函数中使用?
我相信你应该能够使用箭头函数。
export default class C extends Component {
componentDidUpdate() {
...
var node = svg.append('svg')
.append('svg:image')
.attr('xlink:href', (d) => this.dict['foo']);
}
}
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 中局部和全局作用域的概念。