可能嗎?我不確定,因爲D3大量使用this
重寫,這似乎與ES6 spec相沖突。在d3上使用箭頭功能
例如,以下工作正常:
// 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你的例子只是設置在選擇的所有元素的值相同,那不是我想要實現(什麼這就是爲什麼函數用於每個元素的原因) – jarandaf
當我運行您的示例時,我看到的唯一區別是輸出控制檯日誌。但你爲什麼要訪問'''這個'''。這是一個有趣的問題,但我想知道這是一個問題。 – chriskelly
@chriskelly它是一個非常具體的用例(有一些我想要重用的函數,它在svg組中創建了一個複雜的元素結構,我需要'this'來知道我引用的是哪個組,其中將添加新元素)。 – jarandaf