为什么我们在作用于 jQuery 对象的函数中使用 $(this) ?

Why do we use $(this) inside a function acting on a jQuery object?

据我了解,函数内部的this是指调用该函数的对象。因此,例如,在

myObj = { name : "Charlie", getType : function() { return typeof(this); } }; 
console.log(myObj.getType()); 

调用函数 getType 的对象是 myObj,因此 typeof(this)typeof(myObj)

那么,为什么我总是在 jQuery 函数中看到 $(this)?例如,在

$('.not-taller-than-50-pixels').each(function()
{
     if ($(this).height() > 50) $(this).height(50);
});

不是 $('.not-taller-than-50-pixels') return jQuery 对象的数组,因此在 each 中,调用函数是一个 jQuery 对象,因此 this 会引用那个 jQuery 对象,我可以简单地写 if (this.height() > 50) this.height(50); ???

From what I understand, this inside of a function refers to the object invoking the function.

这是正确的,如果该函数作为该对象的 属性 被调用。但是,在您的情况下,您的 jQuery 集合并未将函数作为 jQuery 集合的 属性 调用,而是使用 .apply.call 将其上下文设置为当前正在迭代的元素。

https://github.com/jquery/jquery/blob/1.9.1/src/core.js#L628

它的工作方式类似于 Array.prototype.forEach。我假设相似性是有意为之的,以便大多数也熟悉本机方法的开发人员看起来很熟悉。


这是一个与您的第一个代码段更加内联的示例,它将按照您的预期运行:

$.fn.alertHeight = function () {
  alert(this.height());
}
$('body').alertHeight();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>Hello World!</p>

因为该函数存储在 $ 的原型上,并作为 jQuery 集合的 属性 调用(它是 $ 的实例) this指的是jQuery集合,这样我们就可以直接使用this.height()获取集合中第一个元素的高度。

我们使用 $(this) 因为 this 没有 getter/setter 方法 .height()$() 使所有选定的元素都可以访问 jquery 方法,而普通的 javascript 等价物则没有。尝试 console.log($(this), " VS ", this); 记住 $() 是一个函数。

doesn't $('.not-taller-than-50-pixels') return an array of jQuery objects

不,$('.not-taller-than-50-pixels') 不是 return JQuery 个对象的数组。它 return 是一个 JQuery 对象,可以包含零个、一个或多个 DOM 元素。

and so inside the each the invoking function is a jQuery object and so this would refer to that jQuery object and I can simply write if (this.height() > 50) this.height(50); ???

为 JQuery 对象包装的每个 DOM 元素调用传递给 .each() 的回调函数,当调用回调函数时,DOM 元素用作上下文。也就是说,在回调函数中 this 将引用 DOM 元素,而不是 JQuery 对象。

这在 .each() 函数的 JQuery 文档中有说明:

When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.