[英]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.