[英]Weird behaviour related to scope in javascript and d3.js
我在与d3.js结合的react.js中编写代码。 但是有一个很小但我不了解的行为。
componentWillMount() {
this.setState({
dummyData: [{
price: 13,
age: 43,
etc: 99
},
{
price: 33,
age: 22,
etc: 100
}]
}
componentDidMount () {
this.keys = Object.keys(this.state.dummyData[0]);
console.log(this.keys) // ["price", "age", "etc"]
}
someMethod(){
console.log(this.keys) // ["price", "age", "etc"]
this.svg.append('g')
.selectAll('g')
.data(this.state.dummyData)
.enter()
.append('g')
.attr('transform', d => {
console.log(this.keys); // ["price", "age", "etc"]
return 'translate(' + this.x0(d.name) + ', 0)';
})
.selectAll('rect')
.data( function(d){
console.log(this.keys); // undefined
return this.keys.map( function(key){ return { key: key, value: d[key] }; }); }) // This statement causes an error
.enter()
.append('rect')
.attr('x', function(d){ return this.x1(d.key) })
.attr('y', function(d){ return this.y(d.value) })
.attr('width', this.x1.bandwidth())
.attr('height', function(d){ return height - this.y(d.value) })
.attr('fill', function(d){ return this.z(d.key) });
}
...
从代码中可以看到,this.keys保持其值,直到到达第二个数据调用为止。 我真的不知道那时会发生什么。
这是因为范围和功能在javascript中的工作方式。 如果将函数更改为箭头函数,它将自动绑定作用域,您将看到期望的结果。
简要说明一下:箭头函数会自动在声明它们的地方绑定作用域,而函数没有声明,因此您必须将想要的作用域显式绑定到函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.