构造函数内部的事件处理

Event handling inside constructor

真的很抱歉,但我不明白为什么它不起作用。 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'));

您的变量 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'));

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