OOJavaScript/jQuery事件点击处理程序
我是JS开发新手,我尝试使用OO Javascript使用“类”,我有一个名为“Timeblock”的类,它的构造函数是: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
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语句呢?因为否则它会变成一个全局的,并且每次初始化新的时间块时都会被覆盖。