如果我使用以下函数:
clusters.prototype.shop_iqns_selected_class = function() {
if(this.viewport_width < 980) {
$(this.iqns_class).each(function() {
$(this.iqn).on('click', function() {
if($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
$(this).addClass('selected');
}
});
});
}
}
要向集群函数添加属性,我知道使用 this.viewport_width
我指的是我定义了 this.viewport_width
的父函数,但是当我使用 jQuery 选择器 $(this)
时,我指的是 $.on()
函数的父级吗?
最佳答案
在 JavaScript 中,this
完全由如何调用函数 定义。 jQuery 的 each
函数调用您提供的迭代器函数,将 this
设置为每个元素值,因此在该迭代器函数中,this
没有longer 指的是它在该代码的其余部分中所指的内容。
这很容易用闭包上下文中的变量修复:
clusters.prototype.shop_iqns_selected_class = function() {
var self = this; // <=== The variable
if(this.viewport_width < 980) {
$(this.iqns_class).each(function() {
// Do this *once*, you don't want to call $() repeatedly
var $elm = $(this);
// v---- using `self` to refer to the instance
$(self.iqn).on('click', function() {
// v---- using $elm
if($elm.hasClass('selected')) {
$elm.removeClass('selected');
} else {
$elm.addClass('selected');
}
});
});
}
}
我继续使用 this
来引用每个 DOM 元素,但是您可以接受迭代器函数的参数,所以没有歧义:
clusters.prototype.shop_iqns_selected_class = function() {
var self = this; // <=== The variable
if(this.viewport_width < 980) {
// Accepting the args -----------v -----v
$(this.iqns_class).each(function(index, elm) {
// Do this *once*, you don't want to call $() repeatedly
var $elm = $(elm);
// v---- using `self` to refer to the instance
$(self.iqn).on('click', function() {
// v---- using $elm
if($elm.hasClass('selected')) {
$elm.removeClass('selected');
} else {
$elm.addClass('selected');
}
});
});
}
}
更多阅读(在我的博客中关于 JavaScript 中的 this
的帖子):
关于javascript - 这个选择器的原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10570217/