该对象实现了一个模式来提供事件侦听器。它至少可以在IE 11和Chrome中运行。为什么`this`不等于`Object`,为什么属性`undefined`?
但我不明白为什么和我有两个问题。
在按键事件监听器中,有一个警报显示this
等于[object HTMLInputElement]
而this.element
是undefined
。
- 为什么
this
不等于Object
? - 为什么
this.element
undefined
? (请注意,在init
方法初始化。)
看到这个JSFiddle
这里是JavaScript:
function CustomEditor(id) {
'use strict';
this.element = null;
this.id = id;
this.init();
};
CustomEditor.prototype.addEvent = function (event, callback) {
'use strict';
return this.element.addEventListener(event, callback, false);
};
CustomEditor.prototype.init = function() {
'use strict';
this.element = document.getElementById(this.id);
this.addEvent('keypress', this.onCustomKeyPress);
};
CustomEditor.prototype.onCustomKeyPress = function() {
'use strict';
// alert("keypress event handler");
this.style.backgroundColor = "#000";
this.style.color = "#ff0";
alert('this = ' + this + '\n\nthis.element = ' + this.element);
};
// create and initialize custom editor
ce = new CustomEditor('myInput1');
document.getElementById('myInput1').value = 'a';
alert('ce = ' + ce + '\n\nce.element = ' + ce.element);
编辑:由@Bergi & @lombausch的意见,我了解我在this
和上下文(周末战士在这里)的错误观念。我对我的对象进行了以下修改,现在this
具有我需要的上下文。 (我使用call
而非bind
这样的代码可与旧版浏览器。)
MyObj.prototype.addEvent = function (event, callback, caller) {
'use strict';
if (typeof window.addEventListener === 'function') {
return this.element.addEventListener(event, function() {
callback.call(caller);
}, false);
}
// for older versions of IE, order of test is important
return this.element.attachEvent('on' + event, function() {
callback.call(caller);
});
};
但是,一个新问题:什么样的变化已被该模式提出了onCustomKeypress
到有权访问事件接口/对象?
事件接口是事件侦听器的第一个参数,但我似乎无法将它传递给回调函数。例如,这不起作用:
MyObj.prototype.onCustomKeyPress = function (e) {
我假设你的意思是“等于'ce'”,而不是“对象”? – Bergi 2014-10-02 11:00:30
这就是事件侦听器的工作方式,它们在绑定到的元素的上下文中调用。看到[这个问题](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback)的解决方案 - 或者你真的想知道*为什么*? – Bergi 2014-10-02 11:02:42
这对你来说总的来说是否令人困惑(就像大多数JavaScript新手一样),或者特别是关于“严格使用”为什么没有帮助? – 2014-10-02 11:02:51