这将返回窗口对象

this returns window object

本文关键字:对象 窗口 返回      更新时间:2023-09-26

在我的示例中,我想模拟jQuery.每个方法,因为我创建了JQueryX对象,该对象可以使用类选择器JQueryX(.classname)进行选择并将其添加到其属性selection这是一个数组,现在我被困在this返回窗口对象的行console.log(this, 'i was clicked');

var x = new JQueryX('.drg');
x.each(function() {
    console.log(this);
    this.addEventListener("click", function () {
        console.log(this, 'i was clicked');
    });
});
JQueryX.prototype.each = function (func,paras){
    paras = paras || [];
    for(var i=0; i<this.selection.length; i++) {
        var that = this.selection[i];
        console.log(that);
        func.apply(that,paras);
    }
};

对我来说奇怪的是this如果我从行中调用它,它会返回我想要的对象console.log(this);

这是因为侦听器函数是由窗口调用的,请尝试:

x.each(function() {
    var self = this;
    this.addEventListener("click", function () {
        console.log(self, 'i was clicked')
    });
});

事实上,当您向对象添加回调函数时this.addEventListener(...)在事件追加时调用函数的不是对象本身,而是窗口。所以这就是为什么this是你函数中的窗口。

因此,您必须使用 var self = this; 保存对象的引用,然后在调用回调方法时,它将具有对对象的正确引用。