javascript类实例处理事件不一致 - 这/范围混淆

时间:2016-12-02 23:53:58

标签: javascript events d3.js scope this

(在发布简化后不久编辑。)

标题不是很具体,我道歉但我不确定要具体询问什么。

Full jsfiddle:https://jsfiddle.net/scottbrown0001/byz63qxm/6/

我很困惑为什么下面的代码会产生以下行为:行

      d3.select(this).select('.here').text(name);

放置预期值" Foo 1"和" Foo 2"两个div中每一个的name,但是

      d3.select(this).select('.there').text(thisFoo.name);

始终在两个div中放置相同的实例name

这显然是一个范围问题或其他问题,但我不知道为什么它会像它那样行事。          

  <style>
    div {margin: 20px; }
    .top {margin-top: 40px; }
    </style>

    </head>
<body>

  <div class='top top1'>
    <div class='clicker'>
      CLICK ME
      <div class='here'> HERE </div>
      <div class='there'> THERE </div>
      </div>
    </div>

  <div class='top top2'>
    <div class='clicker'>
      CLICK ME
      <div class='here'> HERE </div>
      <div class='there'> THERE </div>
      </div>
    </div>


  <script src="//d3js.org/d3.v4.min.js"></script>

  <script>

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    d3.selection.prototype.trigger = function(event, detail) {
      var e = new CustomEvent(event, detail);
      this.node().dispatchEvent(e);
      return this;
      }

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    function Foo(where, name) {

      this.name = name;

      var top = d3.select('.' + where);
      var clicker = top.select('.clicker');

      thisFoo = this;

      clicker.on(
        'click',
        function(){
          d3.select(this).select('.here').text(name);
          d3.select(this).select('.there').text(thisFoo.name);
          }
        )

      }

  foo1 = new Foo('top1', 'Foo 1');
  foo2 = new Foo('top2', 'Foo 2');


    </script>

  </body>
</html>

0 个答案:

没有答案