如何正确通过此范围

How to pass the scope of this correctly

本文关键字:范围 何正确      更新时间:2023-09-26

我在以下this范围方面遇到问题:

var test = {
    $divs: $('div'),
    init: function() {
        this.$divs.each(function(){
            $(this).on('click', test.whatsmyid);
            $(window).on("resize", test.whatsmyid);
        });
    },
    whatsmyid: function() {
        console.log($(this).attr("id"));
    }
};
test.init();

http://jsfiddle.net/4NZgd/1/

单击事件正确处理this的范围,但窗口大小调整不会。 我知道原因是this没有传递给窗口调整大小事件,但我不想使用变量将元素传递给whatsmyid,那么我该如何解决这个问题?

这是因为this当被resize调用时是窗口。Windows对象没有id。这就是为什么它返回undefined.

如果要更改函数内部的this,可以使用.bind

$(window).on("resize", test.whatsmyid.bind(this));

小提琴 : http://jsfiddle.net/4NZgd/2/

我知道已经

接受了答案,但是并非每个浏览器都支持.bind,这意味着IE 9以下的任何内容。

所以这是一个替代答案

http://jsfiddle.net/4NZgd/9/

var test = {
$divs: $('div'),
init: function() {
    this.$divs.each(function(){
        var $this = $(this);
        $(this).on('click', test.whatsmyid);
        $(window).on("resize", function () {
            test.whatsmyid.call($this);
        });
    });
},
whatsmyid: function() {
    console.log($(this).attr("id"));
}

};

test.init();

我喜欢

将eventData传递给绑定函数。基本上,eventData 是 javascript PlainObject,您可以传递事件的信息。jQuery bind()

var varModule = {
    $divs: $("div"),
    init: function() {
        var me = this;
        me.$divs.each(function() {
            $(this).bind("click", { me: $(this) }, me.findID);
            $(window).bind("resize", { me: me }, me.findID);
        });
    },
    findID: function(event) {
        var me = event.data.me;    //You will get PlainObject in event.data
        console.log(me.attr("id"));    //div object will give you id but window object wont give you id attribute
    }
};
(function() {
    varModule.init();
})();