这三种形式有什么区别:
this
$this
$(this)
在典型的用法中,您通常会看到它们像这样($this
的用法可能有所不同):
this
- 指当前处理程序中的DOM元素,但在其他情况下可能是完全不同的对象,但它始终是上下文。$this
- 通常由 var $this = $(this)
创建,是jQuery包装版本的缓存,用于提高效率(或在许多情况下使用链式调用$(this)
来获得相同的结果)。$(this)
- 元素的jQuery包装版本,因此您可以访问所有其方法(特别是$.fn
中的方法)。this
是指调用方法的对象。$this
是一个名字不太规范且没有特殊含义的变量。$(this)
调用了一个名字不太规范的函数$
,并将this
作为唯一参数传递给它。this
的jQuery包装版本...你会称它为什么?考虑到 $var
作为 jQuery 对象的常见约定被广泛使用。至于第三点,你建议用什么替代品?有几个库选择了这个(jQuery、MooTools、Prototype、Microsoft's...),肯定有原因。 - Nick Craver在jQuery事件处理程序中:
this
- 是您分配事件处理程序的DOM元素$(this)
- 是从该元素创建的jQuery对象$this
- 通常是一个变量,保存$(this)
的结果更一般地说:
this inside a function refers to the object or primitive the function is called on. When a function is used as a constructor, it refers to the new object being constructed. Outside of any function this
refers to the global object (window
in non-strict mode).
You can find a good detailed explanation on MDN.
$this is a variable name. In JavaScript variable names can start with $
. Some like to use it as a prefix for variables containing jQuery objects:
var body = document.body; // no prefix for a plain DOM object
var $body = jQuery('body'); // prefix for the same object wrapped in jQuery
var $this = $(this);
$(this) is a function call, where $
is a function name, and this
is its argument:
var $ = alert;
$(this); // [object Window]
$
doesn't have any special meaning per se. But jQuery defines the $()
function as a shorthand for jQuery()
. Depending on its arguments, this function can do many different things.
对David所说的进行扩展:
$this
通常用于在当前作用域中拥有this
对象的副本。例如,使用var $this = this;
,您可以在当前作用域中任何地方使用变量$this
,并始终能够引用该对象,否则如果仅使用this
引用,则会更改...我个人不喜欢$this
命名约定,而更喜欢像var parentScope
这样的东西。
$(this)
是一些框架(如jQuery或PrototypeJs)使用的函数(var $ = function(){}
)。之所以使用它,是因为$
比someLongFunctionName
更容易输入,而且由于通常在代码中多次调用它,因此最好尽可能缩短它。
更多上下文会更有助于回答您的问题。
不过我猜您是在询问关于回调函数中变量的问题(例如 click
事件)。
this
是处理程序的上下文(通常是 DOM 元素,在 DOM 事件处理程序的情况下)$this
通常用于存储 $(this)
的结果$(this)
返回包装 this
的 jQuery 对象 - 有关更多信息,请参见 jQuery 文档。
$this
被用来引用父级作用域对象,有点像var that
。然而我能理解 jQuery 现象可能影响了它的含义。 - Luca Matteis