插件开发中的 jQuery $this 与 $(this)

标签 jquery this keyword

我想知道为什么在这么多jquery插件中$(this)被设置为指向$this,这是一个例子,如果我在一个页面上包含以下两个插件:

(function($) {
   jQuery.fn.pluginOne = function() {
      return this.each(function() {
         $this = $(this); <--
         alert($this);
      });
   };
})(jQuery)

(function($) {
   jQuery.fn.pluginTwo = function() {
      return this.each(function() {
         $this = $(this); <--
         alert($this);
      });
   };
})(jQuery)

当我在 dom 上调用两个插件时:

$(document).ready({
   $('.myClass').pluginOne();
   $('.myOtherClass').pluginTwo();
});

第一个插件将从第二个插件获取 $this...同时我将 $(this) 指向本地变量:

(function($) {
   jQuery.fn.pluginTwo = function() {
      return this.each(function() {
         var trigger = $(this); <--
         alert(trigger);
      });
   };
})(jQuery)

当然,一切都应该有效......

所以我的问题是...我什么时候应该使用 $this?

谢谢

最佳答案

$this 是人们用来将实际 jQuery 对象 $(this) 缓存在变量中的标准。

你可以随意命名它,有些人喜欢将其称为 $self。

例如

var $self = $(this)

当您查看代码时,它只会帮助您识别出它是一个 jQuery 对象而不是普通的 dom 对象。

当您只创建 jQuery 变量的一个实例时,它的性能会更好。

关于插件开发中的 jQuery $this 与 $(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1158582/

相关文章:

javascript - 使用 for 循环创建数组的数组

jquery - 如何使用 jsdom 测试导入 jquery 的 es6 模块

javascript - 为什么在执行谷歌地图方向服务回调时DomWindow对象是 'this'

latex - 使用 tlmgr 搜索所有关键字

javascript - 如何在按键时使用 javascript 获取 contenteditable div 中的当前行位置

javascript - 如何使用javascript在输入元素中显示特殊字符?

c++ - 类构造函数不保存变量

angular - "this"不能用于 typescript 函数 (Angular)

c# - 使用 new 关键字调用基本方法

javascript - JavaScript 中的 `name` 关键字是什么?