javascript事件绑定的this

在javascript的事件绑定中,我们经常用到的方法是

function addListener(el, event, fn, bCapture){

var isCapture = bCapture ? bCapture : false;

try {

el.addEventListener(event, fn, isCapture);

}

catch (e) {

try {

el.attachEvent('on' + event, fn);

}

catch (e) {

el['on' + event] = fn;

}

}

}

function whatIsThis(){

if (this === window) {

alert('This is a window object');

}

alert('So, This.tagName is:'+ '‘'+ this.tagName +'’。');

}

addListener(spanEl, 'click', whatIsThis);

但是这个存在一个问题,就是事件处理函数fn中this的指向在不同的浏览器(firefox和ie)中有不同的含义,在ie中this指向的是window对象,这个是不可理解的,一般来说this都是指向当前的元素。

解决办法:

1如果只有一个事件绑定,可以采用elem.onclick=function(e){};

2

function addEvent(el, event, fn, obj, overrideContext, bCapture){

var context = el, isCapture = bCapture ? bCapture : false, wrappedFn = null;

if (overrideContext) {

if (overrideContext === true) {

context = obj;

}

else {

context = overrideContext;

}

}

wrappedFn = function(){

return fn.call(context);

};

try {

el.addEventListener(event, wrappedFn, isCapture);

}

catch (e) {

try {

el.attachEvent('on' + event, wrappedFn);

}

catch (e) {

el['on' + event] = wrappedFn;

}

}

}