⒈ this が指すものを見分ける4つのポイント
⒉ this の基本ルール
⒊ どの this が使われるか判断するコツ
⒋ this を迷わないための対策
⒌ まとめ
this が指すものを見分ける4つのポイント
JavaScriptで this が何を指すのかを決めるルールは、大きく分けて4つあります。
- 関数の呼び方(重要!)
- どこで定義されたかではなく、どのように呼ばれたか
- strict mode (厳格モード) の影響
- this を明示的に指定する方法 ( .call( ), .apply( ), .bind( ) )
this の基本ルール
⒈グローバルスコープ(関数の外側)
//javascript
console.log( this );
・ブラウザでは this は window を指す
・Node.js では this は{}(空のオブジェクト)
⒉通常の関数内
//javascript
function showThis() {
console.log(this);
}
showThis();
・非strict mode → window (または globalThis )
・strict mode ( ” use strict “; を使う) → undefind
⒊オブジェクトのメソッド
//javascript
const obj = {
name: "Alice",
greet: function() {
console.log(this.name);
}
};
obj.greet(); // "Alice"
・メソッドを呼び出したオブジェクト ( obj ) が this になる
⒋コンストラクタ関数
//javascript
function Person(name) {
this.name = name;
}
・new を使って呼び出すと、 this は新しく作られたオブジェクトになる。
⒌アロー関数( this が固定される)
//javascript
const obj = {
name: "Charlie",
greet: () => {
console.log(this.name);
}
};
obj.greet(); // undefined
・アロー関数の this は定義された場所の this を引き継ぐ
・オブジェクトのメソッドとして使っても、 this は obj にならない!
⒍明示的に this を変更する
//javascript
function showThis() {
console.log(this.name);
}
const user = { name: "David" };
showThis.call(user); // "David"
showThis.apply(user); // "David"
const boundFunc = showThis.bind(user);
boundFunc(); // "David"
・.call() や .apply() を使うと this を好きなオブジェクトに変更できる
・.bind() は this を固定する
どの this が使われるか判断するコツ
質問:「この関数はどのように呼び出される?」
⒈通常の関数 → window ( strict mode なら undefind )
⒉オブジェクトのメソッド → 呼び出し元のオブジェクト
⒊コンストラクタ( new 付き)→ 新しいオブジェクト
⒋アロー関数 → this は外側のスコープから継承
⒌ call / apply / bind → 指定されたオブジェクト
this を迷わないための対策
⒈アロー関数を活用する(特に this の変更を避けたいとき)
⒉オブジェクトのメソッドにするときはアロー関数を避ける
⒊明示的に .bind() を使うと安全
⒋ console.log( this ) を実験して確認する
まとめ
・this は「関数がどのように呼ばれるか」によって決まる
・this のルールを理解するには「呼び出し方」に注意する
・アロー関数は this を固定するので、使い方に注意
このルールを意識しながらコードを書けば、 this の混乱を防ぐことができます!!
コメント