首页  >  文章  >  web前端  >  “this”在 jQuery 和常规 JavaScript 中的行为有何不同,以及使用 DOM 元素和函数调用有何影响?

“this”在 jQuery 和常规 JavaScript 中的行为有何不同,以及使用 DOM 元素和函数调用有何影响?

Susan Sarandon
Susan Sarandon原创
2024-10-26 08:18:02838浏览

How does

理解 jQuery 和 JavaScript 中的“this”

在 jQuery 中,“this”通常指与函数关联的 DOM 元素被召唤。例如,在事件回调中,“this”代表触发事件的元素。

示例:

<code class="javascript">$("div").click(function() {
  // Here, `this` will be the DOM element for the div that was clicked,
  // so you could (for instance) set its foreground color:
  this.style.color = "red";
});</code>

jQuery 在函数中也使用“this”像 html() 和 every():

示例 (html):

<code class="javascript">$("#foo div").html(function() {
  // Here, `this` will be the DOM element for each div element
  return this.className;
});</code>

示例(每个):

<code class="javascript">jQuery.each(["one", "two", "three"], function() {
  // Here, `this` will be the current element in the array
  alert(this);
});</code>

通用 JavaScript 中的“this”

在 jQuery 之外,JavaScript 中的“this”通常指代一个对象。然而,在 ES5 的严格模式下,这并不是严格正确的,其中“this”可以有任何值。

函数调用中“this”的值取决于函数的调用方式。它可以通过对象属性调用函数来显式设置,也可以默认为全局对象(浏览器中的窗口)。

示例:

<code class="javascript">var obj = {
  firstName: "Fred",
  foo: function() {
    alert(this.firstName);
  }
};

obj.foo(); // alerts "Fred"</code>

在此示例中,“this”被显式设置为 obj 对象,因此它可以访问 firstName 属性。

但是,需要注意的是,函数 foo 本质上并不与任何特定对象绑定。可以使用 .call 和 .apply 等函数使用不同的“this”值来调用它:

<code class="javascript">function foo(arg1, arg2) {
  alert(this.firstName);
  alert(arg1);
  alert(arg2);
}

var obj = {firstName: "Wilma"};
foo.call(obj, 42, 27); // alerts "Wilma", "42", and "27"</code>

在此示例中,使用 obj 对象作为“this”调用 foo,从而允许它访问firstName 属性。

ES5 的严格模式引入了进一步的复杂性,允许“this”具有非对象值(如 null、未定义)或基元(如字符串和数字):

<code class="javascript">(function() {
  "use strict";   // Strict mode

  test("direct");
  test.call(5, "with 5");
  test.call(true, "with true");
  test.call("hi", "with 'hi'");

  function test(msg) {
    console.log("[Strict] " + msg + "; typeof this = " + typeof this);
  }
})();</code>

输出:

[Strict] direct; typeof this = undefined
[Strict] with 5; typeof this = number
[Strict] with true; typeof this = boolean
[Strict] with 'hi'; typeof this = string

在严格模式下,“this”由调用点而不是函数的定义决定,并且它可以有非对象值。

以上是“this”在 jQuery 和常规 JavaScript 中的行为有何不同,以及使用 DOM 元素和函数调用有何影响?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn