🚀
thisとは
thisとは
- thisは
読み取り専用のグローバル変数のようなもの
┗ 「今、このコードが動いているのが、誰(何)の中なのか」を指すもの
thisの参照先とは
- thisの参照先は実行コンテキストによって異なる
スクリプトの場合
- 通常の<script>タグ(Script)の場合、
this=window
スクリプトの場合
function test() {
console.log(this)
}
これをブラウザで呼び出すと
スクリプトの場合
test() // => Window {frames: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}
つまりこのthisはグローバルオブジェクト、ブラウザではwindowオブジェクトとなる
モジュールの場合
- thisは
undefinedになる
モジュールの場合
function test() {
console.log(this)
}
これをブラウザで呼び出すと
モジュールの場合
console.log(this); // => undefined
※ 単純にグローバルオブジェクトを参照したい場合は、thisではなくglobalThisを使います。
関数とメソッドにおけるthis
関数の種類
| 種類 | 関数の記述方法 |
|---|---|
| 関数宣言 | function fn1() {} |
| 関数式 | const fn2 = function() {}; |
| アロー関数 | const fn3 = () => {}; |
メソッドとは
オブジェクトの中に定義された関数のこと
メソッドについて
const obj = {
// 普通のメソッドの書き方
method1: function() {
// thisはobjを指すことが多い
},
// アロー関数を使ったメソッド(これはthisの挙動が特殊なので注意!)
method2: () => {
// thisはobjを指さないことが多い
},
// メソッドの短縮記法(最近よく使われる)
method() {
// thisはobjを指すことが多い
}
};
オブジェクトに紐づいたthis
📝 .(ドット)の直前にあるオブジェクトがthisになる
オブジェクトの場合
オブジェクト.メソッド()
↑ ↑
ベースオブジェクト この時のthisは左のオブジェクトを指す
具体例
オブジェクトの場合
const person = {
fullName: "Brendan Eich",
sayName: function() {
return this.fullName; // person.fullNameと同じ
}
};
console.log(person.sayName()); // => "Brendan Eich"
Discussion