【发布时间】:2009-06-09 14:44:32
【问题描述】:
我正在创建一个 JavaScript 类(使用 Prototype),如果在指定的秒数内没有鼠标移动,它会将页面状态设置为空闲。当鼠标移动时,该类将通过向侦听器列表发送消息来“唤醒”页面。
我不明白的是,this.handlers 在一个函数 (setIdle) 中有效,但在另一个函数 (setActive) 中无效。下面带注释的代码说明了我的问题:
var IM2 = Class.create({
handlers: null,
initialize: function(callback, frequency) {
this.handlers = [];
Event.observe(document, "mousemove", this.sendActiveSignal);
Event.observe(document, "keypress", this.sendActiveSignal);
setInterval(this.sendIdleSignal.bind(this), 5000);
},
addListener: function(h) {
console.log(this.handlers.size()); // it's 0 here, as expected
this.handlers.push(h);
console.log(this.handlers.size()); // it's 1 here, as expected
},
sendIdleSignal: function(args) {
console.log("IDLE");
this.handlers.each(function(i){
i.setIdle();
})
},
sendActiveSignal: function() {
// this.handlers is undefined here. Why?
this.handlers.each(function(r) {
r.setActive();
})
}
});
【问题讨论】:
-
对象末尾有一个额外的逗号,这可能会产生一些奇怪的错误,但我怀疑这就是问题所在。如果您在 sendActive() 中执行 console.log(this),会记录什么?
标签: javascript scope prototypejs