【发布时间】:2014-02-21 20:43:14
【问题描述】:
我正在尝试创建一个小型库,我现在正在使用 event 方法向元素添加事件。
现在,当使用如下代码时,正确返回我的库对象的实例。
event: function (event, callback, sync) {
var _this, len;
_this = this;
len = this.length;
if (document.addEventListener) {
if (len > 1) {
while (len--) {
this[len].addEventListener(event, callback, sync);
}
} else {
this[0].addEventListener(event, callback, sync);
}
} else if (window.attachEvent) {
if (this.length > 1) {
while (this.length--) {
this[this.length].attachEvent('on' + event, function () {
callback.call(window.event.srcElement);
});
}
} else {
this[0].attachEvent('on' + event, callback);
}
} else {
console.log(false);
return false;
}
return this;
}
但是当添加一个小代码时并没有正确返回我的库对象的实例,而是返回 windows 对象。
event: function (event, callback, sync) {
var _this, len;
_this = this;
len = this.length;
if (document.addEventListener) {
if (len > 1) {
while (len--) {
this[len].addEventListener(event, function (e) { // <<-- From here
var e = e.target;
_this[0] = e;
_this.length = 1;
callback();
}, sync);
delete this[len];
} // <<-- to here
} else {
this[0].addEventListener(event, callback, sync);
}
} else if (window.attachEvent) {
if (this.length > 1) {
while (this.length--) {
this[this.length].attachEvent('on' + event, function () {
callback.call(window.event.srcElement);
});
}
} else {
this[0].attachEvent('on' + event, callback);
}
} else {
console.log(false);
return false;
}
return this;
}
这部分的问题
this[len].addEventListener(event, function (e) {
var e = e.target;
_this[0] = e;
_this.length = 1;
callback();
}, sync);
delete this[len];
}
使用时
HTML
<div id="box">
<span class="box"> span</span>
<span class="box">span 2</span>
<span class="box">span 3</span>
</div>
JS
oo('.box').event('click', function () {
console.log(this); // this return the windows object not my library object.
});
【问题讨论】:
标签: javascript object this