【发布时间】:2015-12-29 02:53:40
【问题描述】:
有可能吗?我不确定,因为 d3 大量使用 this 重新绑定,这似乎与 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 对象):
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
相关小提琴here.
【问题讨论】:
-
@chriskelly 您的示例只是为选择中的所有元素设置相同的值,这不是我想要实现的(这就是为什么在每个元素的基础上使用函数)
-
当我运行您的示例时,我看到的唯一区别是输出控制台日志。但是你为什么要访问
this。这是一个有趣的问题,但我想知道一个问题所在。 -
@chriskelly 这是一个非常具体的用例(有一些我想重用的函数,它在 svg 组中创建复杂的元素结构,我需要
this知道我引用的是哪个组,其中将追加新元素)。
标签: javascript d3.js ecmascript-6