简体   繁体   English

如何正确传递这个范围

[英]How to pass the scope of this correctly

I'm having trouble with the scope of this in the following: 我在与范围的麻烦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/ http://jsfiddle.net/4NZgd/1/

The click event handles the scope of this correctly but the window resize doesn't. 单击事件处理的范围this正常,但窗口大小调整没有。 I understand the reason is that this isn't being passed to the window resize event but I don't want to pass the element to whatsmyid using a variable so how do I get around this? 我理解的原因是this不是传递给窗口调整大小事件但是我不想使用变量将元素传递给whatsmyid所以我该如何解决这个问题呢?

That is because this when called by resize is the window. 这是因为this时称为resize为窗口。 Windows object doesnt have id 's. Windows对象没有id That's why it return undefined . 这就是为什么它返回undefined

if you want to change the this inside the function, you can use .bind : 如果你想改变this函数里面,你可以使用.bind

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

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

I know an answer has already been accepted for this however not every browser supports .bind meaning anything below IE 9. 我知道答案已被接受,但并非每个浏览器都支持.bind意味着IE 9以下的任何内容。

so here's an alternative answer 所以这是一个替代答案

http://jsfiddle.net/4NZgd/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(); test.init();

I like to pass eventData to the bind function. 我喜欢将eventData传递给bind函数。 Basically, eventData is javascript PlainObject and you can pass information for the event. 基本上,eventData是javascript PlainObject,您可以传递事件的信息。 jQuery bind() 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();
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM