Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
OOJavaScript/jQuery事件点击处理程序_Javascript_Jquery - Fatal编程技术网

OOJavaScript/jQuery事件点击处理程序

OOJavaScript/jQuery事件点击处理程序,javascript,jquery,Javascript,Jquery,我是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

我是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
时,我也会得到
未定义的
,但如果我键入
this.occulated
时,我会得到
false

我的问题是,为什么我没有定义?我怎么才能让它工作呢?我搜索了又搜索,但找不到任何学习OOJavaScript的好材料

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');
  }
}
两个错误。我修正了它们,并留下了解释的评论


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

Thaks,它可以工作,但是为什么需要var语句呢?因为否则它会变成一个全局的,并且每次初始化新的
时间块时都会被覆盖。Thaks,它可以工作,但是为什么需要var语句呢?因为否则它会变成一个全局的,并且每次初始化新的
时间块时都会被覆盖。