javascript 类实例处理事件不一致 - this/范围界定困惑

标签 javascript events d3.js scope this

(发布后不久进行编辑以简化。)

标题不是很具体,我很抱歉,但我不确定要更具体地问什么。

完整的jsfiddle:https://jsfiddle.net/scottbrown0001/byz63qxm/6/

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

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

name 的预期值“Foo 1”和“Foo 2”放置在两个 div 中的每一个中,但该行

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

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

很明显,这是一个范围问题或其他问题,但我无法理解它为什么会这样。

  <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>

最佳答案

因为你没有使用var声明时关键字 thisFoo ,您将其设为全局变量:

Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.

所以发生的事情是 foo1 = new Foo('top1', 'Foo 1'); 行执行后thisFoo是对新创建的 Foo 的引用目的。以下行foo2 = new Foo('top2', 'Foo 2');更改全局变量 thisFoo 的值这样它就成为对第二个 Foo 的引用对象。

如果您确保使用var,您的代码应该按照您想要的方式工作。关键字以确保 thisFoo绑定(bind)到Foo的函数范围。

关于javascript 类实例处理事件不一致 - this/范围界定困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40942660/

相关文章:

javascript - 删除逗号分隔字符串末尾和开头的空格和逗号

javascript - 动态创建的元素上的事件绑定(bind)?

javascript - d3 : graph looks good in firefox but is cut off in chrome

javascript - JS 定位特定 div 中的图像,即使它们共享类

javascript - 使用 'moment.js' 将自定义日期戳添加到 node.js

javascript - 将数组从 javascript 传递到 servlet

c++ - 如何在 C/C++ 中检查 USB 是否插入或移除

Javascript - 覆盖先前在另一个函数中声明的样式

javascript - d3 js 知道一个 svg 形状是否有一个类

javascript - 选择.追加/插入 : d3 changes from v3 to v4 turns checkboxes into text fields