OO Javascript/jQuery事件点击处理程序

OO Javascript / jQuery event click handler

本文关键字:处理 程序 事件 Javascript jQuery OO      更新时间:2023-09-26

我是JS开发的新手,我试图使用"类"使用OO Javascript,我有一个名为"Timeblock"的类,它的构造函数是:

var Timeblock = function(occupied, on, element) {
  this.occupied = occupied;
  this.on = on;
  this.room_id = 0;
  this.element= element;
}

我用这种方式创建了一个对象:

timeblock = new Timeblock(false, false, $('#element'));

在这一点上一切都正常,现在我正试图在类构造函数的元素var上添加一个点击事件监听器,我尝试了:

var Timeblock = function(occupied, on, element) {
  this.occupied = occupied;
  this.on = on;
  this.room_id = 0;
  this.element = element;
  timeblock = this;
  this.element.click(function() {
      timeblock.update();
  });
}
Timeblock.prototype.update = function() {
  if (!occupied) {
    this.element.addClass('on');
  }
}

在Chrome中调试时,我在this.element.addClass('on');上设置了一个断点,检查我可以读取this.element: jQuery.fn.init[0]的对象,但我无法使其工作。

即使在控制台中,当我键入this.element时,我也会得到undefined,但如果我键入this.occupied,我就会得到false

我的问题是,为什么我变得不明确?我怎样才能让它工作?,我找了又找,但找不到任何好的材料来学习OO Javascript。

var Timeblock = function(occupied, on, element) {
  this.occupied = occupied;
  this.on = on;
  this.room_id = 0;
  this.element = element;
  var timeblock = this; // need var statement
  this.element.click(function() {
      timeblock.update();
  });
}
Timeblock.prototype.update = function() {
  if (!this.occupied) { // forgot this
    this.element.addClass('on');
  }
}

两个错误。我修复了它们,并留下了解释性的评论。