function(){}和()=> {},是一样的吗?

时间:2018-12-11 14:36:32

标签: javascript

我有一个正在使用的学习代码:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://d3js.org/d3.v5.min.js"></script>
  </head>
  <body>

    <script type="text/javascript">
      var svg = d3.select('body').append('svg').attr('width', 500).attr('height', 500);

      var data = [30, 20, 40];

      var circles = svg.selectAll('circle')
        .data(data).enter()
        .append('circle')
          .attr('cx', (d, i) => i * 30 + 20)
          .attr('cy', 30)
          .attr('r', d => d / 2)
          .style('fill', 'steelblue');

      circles.on('mouseenter', () => {
        d3.select(this).style('fill', 'red');
      });
      circles.on('mouseout', function() {
        d3.select(this).style('fill', 'steelblue');
      })
    </script>
  </body>
</html>


mouseenter函数不起作用,但是mouseout函数很好。
请告诉我function() {}与()=> {}

的区别

2 个答案:

答案 0 :(得分:0)

区别在于this在(fat)箭头函数中的词汇用法。

Jake在这里做了完美的解释-What is lexical 'this'?

答案 1 :(得分:0)

一个区别是function(){}拥有自己的this,其中()=> {}从被调用的地方获取thisarticle进一步详细说明了两者之间的区别。

相关问题