首頁  >  文章  >  web前端  >  「this」關鍵字在 jQuery 和 JavaScript 中的行為如何?

「this」關鍵字在 jQuery 和 JavaScript 中的行為如何?

Patricia Arquette
Patricia Arquette原創
2024-10-26 19:41:29348瀏覽

How Does the

「this」在 jQuery 中代表什麼?

在 jQuery 中,「this」代表作為函數主題的 DOM 元素被召喚。這通常用於事件回調和作用於多個元素的函數。例如:

<code class="javascript">$("div").click(function() {
  this.style.color = "red";
});</code>

這會將點擊的元素的前景色設為紅色。

一般在 JavaScript 中

在 JavaScript 中,「this " 指的是呼叫函數的物件。這是由函數的呼叫方式決定的,而不是由函數的定義位置決定的。

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

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

在此範例中,當呼叫 foo 時,「this」被設定為 obj。但是,「this」的值可以是任何對象,包括全域對象(瀏覽器中的視窗)。

<code class="javascript">f(); // Probably alerts "undefined"

//... Later

var obj = {
  firstName: "Wilma"
};

f = obj.foo;
f(); // alerts "Wilma"</code>

在上面的範例中,f 是 foo 函數的參考。當在沒有物件屬性的情況下呼叫 f 時,「this」預設為全域物件。

ES5 嚴格模式

在 ES5 嚴格模式中,「this」可以是任何值,包括非物件。如果「this」沒有明確設置,則預設為未定義。

<code class="javascript">"use strict";

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

test(); // typeof this = undefined
test.call(5); // typeof this = number</code>

在常規(非嚴格)模式下,所有這些呼叫都會傳回 typeof this = object。

以上是「this」關鍵字在 jQuery 和 JavaScript 中的行為如何?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn