首頁 > web前端 > js教程 > 主體

「this」在 jQuery 和常規 JavaScript 中的行為有何不同,以及使用 DOM 元素和函數呼叫有何影響?

Susan Sarandon
發布: 2024-10-26 08:18:02
原創
837 人瀏覽過

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>
登入後複製

通用Java

在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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!