对此选择器进行原型设计

prototype this selector

本文关键字:原型 选择器      更新时间:2023-09-26

如果我使用以下函数:

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不再引用它在其余代码中引用的内容。

这很容易在闭包的上下文中使用变量来解决:

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的文章):

  • 神话般的方法
  • 你必须记住this

不要在整个代码中使用this。像$.each这样的方法给你另一个参考:

$(".foo").each(function(index, element){
  /* 'element' is better to use than 'this'
     from here on out. Don't overwrite it. */
});

此外,$.on通过事件对象提供相同的功能:

$(".foo").on("click", function(event) {
  /* 'event.target' is better to use than
     'this' from here on out. */
});

当你的嵌套深入时,有太多的歧义,无法使用this。当然,你会发现另一种正在使用的方法是直接在回调中创建 that 的别名,它等于 this

$(".foo").on("click", function(){
  var that = this;
  /* You can now refer to `that` as you nest,
     but be sure not to write over that var. */
});

我更喜欢在参数或事件对象中使用 jQuery 提供的值。