JavaScript の this が他の OOP 言語と異なる理由
JavaScript の this
キーワードは、特に self
が一貫して現在のオブジェクト インスタンスを参照する C#、Java、または Python などの言語から来た開発者にとって、混乱を引き起こすことがよくあります。 これらの言語とは異なり、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 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









