我正在创建一个小型工具提示应用程序,并且遇到了问题。我试图给文档添加一个事件,但是在引用需要执行的函数时遇到了问题。下面是代码:如何使用'this'关键字进行函数引用
var Note, note;
(function() {
'use strict';
// Helper functions
function addEvent(to, type, fn) {
if (to.addEventListener) {
to.addEventListener(type, fn, false);
} else if (to.attachEvent) {
to.attachEvent('on' + type, fn);
} else {
to['on' + type] = fn;
}
}
// Temporary constructor
function Temp() {
this.dragging = false;
return this;
}
Temp.prototype = {
listen: function() {
this.dragging = true;
},
drag: function() {
alert('hi 1');
if (!this.dragging) return;
alert('hi 2');
},
create: function() {
// unimportant code ...
addEvent(document, 'mousedown', this.drag);
// unimportant code ...
}
};
window.Note = Temp;
}());
note = new Note();
note.create(); // the note is created as planned
note.listen(); // alert(note.dragging) yields true
如果在代码中的小失误,我不认为这些都是问题,在我的系统代码通过JSLint的(我知道这并不能保证正确性)。这两种警报都没有提醒他们的论点。不过,我怀疑问题在于将this.drag分配给事件处理程序的函数引用。有没有解决这个问题的方法?
谢谢大家的时间!
你的代码工作正常,在我的IE9,Chrome和Firefox。 –
@Robby,D:没办法,我在用镀铬。 。 。 > _> – dunnza