d3.select(this)不能用箭头函数

d3中典型的数据绑定片段

    const items = svg.selectAll('g')
                    .data(gdfs,(d)=> d.name);

    const enter = items.enter().append('g');
    //console.log(enter);
    //没有update()函数了,添加删除后,全部更新
    enter.merge(items)
        .attr('class',(d)=> d.name)
        .each(function(d) {
            const g = d3.select(this);
            console.log('g',g);
            //do some with g;
        });

    items.exit().remove();
}

对g元素如果需要进一步绑定数据进行操作,则调用each 传入匿名函数。 里面使用d3.select(this) ,这个d3 选择集,指向each对应的dom元素。

在这里,要注意this的问题。如果使用es6的箭头函数() =>{} ,会报错,必须使用传统的funcion(d){}

区别在这里,箭头函数不绑定this  https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions

 

不绑定this

在箭头函数出现之前,每个新定义的函数都有它自己的 this

箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this

 

但是d3这里,显然是依赖局部的this的,用箭头函数,是找上一层的this,会报错。

 

 

——总之,用d3.select(this)的地方,就用传统的function就好了。反正也不是很多。

 

posted @ 2018-11-10 09:20  永远的幻想  阅读(592)  评论(0编辑  收藏  举报