JavaScript 的 this
關鍵字經常會造成混亂,特別是對於來自 C#、Java 或 Python 等語言的開發人員來說,其中 self
總是指涉目前物件實例。 與這些語言不同,JavaScript 的 this
是動態的,其值由函數的呼叫上下文決定。本指南總結了影響 this
行為的各種場景。
1。全球範圍:
-
非嚴格模式:
this
指向全域物件(瀏覽器中為window
,Node.js 中為global
)。
console.log(this); // window or global
-
嚴格模式:
this
是undefined
。
"use strict"; console.log(this); // undefined
2。內部函數:
-
常規函數:非嚴格模式下,
this
指的是全域物件;在嚴格模式下,它是undefined
。
function myFunc() { console.log(this); } myFunc(); // window (non-strict), undefined (strict)
3。物件方法:
- 當函數作為物件方法呼叫時,
this
引用該物件。
const myObj = { name: "JavaScript", greet() { console.log(this.name); // this refers to myObj } }; myObj.greet(); // Output: JavaScript
4。箭頭功能:
- 箭頭函數缺少自己的
this
。它們從詞法範圍(周圍上下文)繼承this
。
const myObj = { name: "JavaScript", arrowFunc: () => { console.log(this.name); // Inherits this from the global scope } }; myObj.arrowFunc(); // undefined (in browsers, this is window)
5。建構子:
- 在建構子或類別中,
this
指的是新建立的實例。
class Person { constructor(name) { this.name = name; } greet() { console.log(`Hello, ${this.name}`); } } const person = new Person("Alice"); person.greet(); // Output: Hello, Alice
6。明確綁定(call
、apply
、bind
):
JavaScript 函數是具有方法 (call
、apply
、bind
) 的對象,用於明確設定 this
.
-
call
和apply
使用指定的this
值呼叫函數。call
使用逗號分隔的參數;apply
接受一個陣列。
function greet(greeting) { console.log(`${greeting}, ${this.name}`); } const user = { name: "Alice" }; greet.call(user, "Hello"); // Output: Hello, Alice greet.apply(user, ["Hi"]); // Output: Hi, Alice
-
bind
傳回一個與this
永久綁定的新函數。
const boundGreet = greet.bind(user); boundGreet("Hello"); // Output: Hello, Alice
7。事件監聽器:
-
常規函數:
this
指觸發事件的元素。
const btn = document.querySelector("button"); btn.addEventListener("click", function() { console.log(this); // The button element });
-
箭頭函數:
this
繼承自周圍範圍,而不是元素。
btn.addEventListener("click", () => { console.log(this); // this depends on the arrow function's definition context });
8。 setTimeout
/ setInterval
:
-
常規函數:
this
預設為全域物件。
setTimeout(function() { console.log(this); // window in browsers }, 1000);
-
箭頭函數:
this
依詞法繼承。
setTimeout(() => { console.log(this); // Inherits this from surrounding context }, 1000);
9。班級:
- 在類別方法中,
this
指的是類別實例。
console.log(this); // window or global
10。上下文遺失(方法擷取):
將方法分配給變數或將其作為回調傳遞可能會導致this
綁定丟失。
"use strict"; console.log(this); // undefined
解決方案:使用.bind(obj)
或箭頭函數來維護上下文。
11。 new
關鍵字:
將 new
與函數一起使用會建立一個新對象,並且 this
引用該對象。
function myFunc() { console.log(this); } myFunc(); // window (non-strict), undefined (strict)
總表:
Context |
this Refers To |
---|---|
Global (non-strict) | Global object (window/global) |
Global (strict) | undefined |
Object Method | The object owning the method |
Arrow Function | Lexical scope (surrounding context) |
Constructor/Class | The instance being created |
call , apply , bind
|
Explicitly defined value |
Event Listener | The element triggering the event |
setTimeout /setInterval
|
Global object (regular function), lexical scope (arrow function) |
new Keyword |
The newly created object |
未定義
呼叫
、應用
、綁定
setTimeout
/setInterval
關鍵字
this
理解這些場景對於編寫正確且可預測的 JavaScript 程式碼至關重要。 請記住在必要時使用顯式綁定等技術以避免意外的行為。 以上是為什麼 JavaScript 中的「this」與其他 OOP 語言不同的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

JavaScript不需要安裝,因為它已內置於現代瀏覽器中。你只需文本編輯器和瀏覽器即可開始使用。 1)在瀏覽器環境中,通過標籤嵌入HTML文件中運行。 2)在Node.js環境中,下載並安裝Node.js後,通過命令行運行JavaScript文件。

如何在Quartz中提前發送任務通知在使用Quartz定時器進行任務調度時,任務的執行時間是由cron表達式設定的。現�...

在JavaScript中如何獲取原型鏈上函數的參數在JavaScript編程中,理解和操作原型鏈上的函數參數是常見且重要的任�...

在微信小程序web-view中使用Vue.js動態style位移失效的原因分析在使用Vue.js...

在Tampermonkey中如何對多個鏈接進行並發GET請求並依次判斷返回結果?在Tampermonkey腳本中,我們經常需要對多個鏈...


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

記事本++7.3.1
好用且免費的程式碼編輯器