【问题标题】:Event handling inside constructor构造函数内的事件处理
【发布时间】:2015-03-20 00:15:03
【问题描述】:

我真的很抱歉,但我不知道为什么它不起作用。 printStr() 只能访问在 Foo 构造函数中定义的变量,但不能访问在 mousedown 事件上触发的私有函数中的变量。有没有什么方法可以访问string 而无需在getBotheredByBrendanEich func 中声明printStr

function Foo(elem) {
  elem.on('mousedown', getBotheredByBrendanEich);

  function getBotheredByBrendanEich() {
    var string = 'its just werks!';
    elem.on('mouseup', printStr);
  }

  function printStr() {
    console.log(string);
  }
}

var test = new Foo($('#test'));

【问题讨论】:

    标签: javascript events closures private


    【解决方案1】:

    您的变量 string 是函数 get...() 内的局部变量,并且仅在该范围内可用。局部变量仅在声明它们的函数中可用,在这种情况下是您的 get...() 函数

    如果您希望它在更广泛的范围内可用,以便printStr() 可以使用它,那么您必须在更高的范围内声明它。

    您可以通过使用在同一范围内声明的匿名函数来解决此问题:

    function Foo(elem) {
      elem.on('mousedown', getBotheredByBrendanEich);
    
      function getBotheredByBrendanEich() {
        var str = 'its just werks!';
        elem.on('mouseup', function() {
          console.log(str);
        });
      }
    }
    
    var test = new Foo($('#test'));
    

    或者,您可以使用 .bind() 将参数传递给事件处理程序:

    function Foo(elem) {
      elem.on('mousedown', getBotheredByBrendanEich);
    
      function getBotheredByBrendanEich() {
        var string = 'its just werks!';
        elem.on('mouseup', printStr.bind(this, string));
      }
    
      function printStr(arg) {
        console.log(arg);
      }
    }
    
    var test = new Foo($('#test'));
    

    或者,您可以将变量移动到更高的范围以便共享:

    function Foo(elem) {
      elem.on('mousedown', getBotheredByBrendanEich);
    
      var str = 'its just werks!';
    
      function getBotheredByBrendanEich() {
        elem.on('mouseup', printStr);
      }
    
      function printStr() {
        console.log(str);
      }
    }
    
    var test = new Foo($('#test'));
    

    但在所有情况下,这种结构都很麻烦,因为每次发生 mousedown 事件时,您都会添加一个新的 mouseup 事件处理程序。这意味着您只需单击几下即可获得多个 mouseup 处理程序。这很少是你真正想做的事情。

    我建议这个不会遇到这个问题:

    function Foo(elem) {
      var str = 'its just werks!';
    
      elem.on('mousedown', function() {
          // whatever code you want here
      });
      elem.on('mouseup', function() {
          console.log(str);
      });
    }
    
    var test = new Foo($('#test'));
    

    还有一条评论。您的代码没有显示在此处实际使用构造函数的任何理由。由于没有对象实例数据,您似乎可以只实现一个普通的函数调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      相关资源
      最近更新 更多