问题描述
有可能吗?我不确定,因为 d3 大量使用 this
重新绑定,这似乎与 ES6 规范.
Is it possible? I am not sure, since d3 makes heavy use of this
rebindings and this seems to conflict with ES6 spec.
例如,以下工作正常:
// Working fine
var data = [1,2,3]
var svg = d3.select('body').append('svg').attr('height', 500).attr('width', 500).style('background-color', 'orange');
var gs = svg.selectAll('g').data(data).enter();
gs.append('circle')
.attr('cx', function () { return Math.random()*500; })
.attr('cy', function () { return Math.random()*500; })
.attr('r', function () { return Math.random()*100; })
.each(function () { console.log(this); }); // this is bound to the current element in the enter selection
虽然以下没有按预期工作(this
未绑定到输入选择中的当前元素,而是绑定到 Window
对象):
While the following does not work as expected (this
is not bound to the current element in the enter selection but to Window
object):
var data = [1,2,3]
var svg = d3.select('body').append('svg').attr('height', 500).attr('width', 500).style('background-color', 'blue');
var gs = svg.selectAll('g').data(data).enter();
gs.append('circle')
.attr('cx', () => Math.random()*500)
.attr('cy', () => Math.random()*500)
.attr('r', () => Math.random()*100)
.each(() => console.log(this)); // this is bound to Window object
相关小提琴这里.
推荐答案
如果您不需要访问当前元素的this
,您可以使用箭头函数.
You can use arrow functions if you don't need access to this
of the current element.
在您想要访问当前元素的 this
的情况下回退到旧样式函数.
Fallback to the old style functions for cases where you want to access this
of the current element.
或者使用显式绑定允许您的函数(不是箭头函数)使用.bind()
Or use explicit binding to allow your function (not arrow function) to access whatever object you want using .bind()
为了避免使用 this
,您可以选择使用 d3 名称或类选择器来方便地访问任何元素.例如:
To avoid working with this
you have the option of using d3 name or class selectors to conveniently access any element. e.g.:
var stuffINeed = svg.selectAll('.someClass');
这篇关于在 d3 中使用箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!