0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【JavasScript】thisについて

Last updated at Posted at 2023-04-27

はじめに

この記事はJS初級者が中級者を目指して学習した内容のメモであることをご承知おき下さい

JavaScriptのthisについて

目次

  1. 概要
  2. 実行コンテキストごとのthis
    1. グローバルスコープ内のthis
    2. 関数スコープ内のthis
    3. メソッド内のthis
    4. イベントハンドラー内のthis
  3. その他の補足
    1. アロー関数とthis
    2. callapplybindを使ったthisの制御
    3. クラス内のthis

概要

JavaScriptのthisキーワードは現在の実行コンテキストに関連するオブジェクトを参照します。thisの値は関数が呼び出される状況によって異なります。以下によくある状況を記載します。

実行コンテキストごとのthis

グローバルスコープ内のthis

グローバルスコープでは、thisはグローバルオブジェクトを参照します。
(ブラウザ環境ではwindowオブジェクトを参照します)

console.log(this); // windowオブジェクトを参照する

関数スコープ内のthis

通常の関数内でthisを使用すると、thisはグローバルオブジェクトを参照します。
ただし、strictモードで実行される関数内のthisundefinedになります。

function fn(){
  console.log(this); // windowオブジェクトを参照する
}
fn();

メソッド内のthis

オブジェクトのメソッド内でthisを使用すると、thisはそのメソッドを呼び出したオブジェクトを参照します。

const person = {
  name: 'Bob',
  greet: function(){
    console.log('Hello I am ' + this.name); // 'Hello I am Bob'(thisは定数personを参照する)
  }
}
person.greet();

イベントハンドラー内のthis

DOM要素に紐づけられたイベントハンドラー内でthisを使用すると、thisはイベントをトリガーした要素を参照します。

const btn = document.querySelector('button');
btn.addEventListener('click', function(){
  console.log(this); // クリックしたbutton要素のhtml(<button></button>)が表示される
})

その他の補足

アロー関数とthis

アロー関数は、通常の関数と異なり、自身のthisを持ちません。アロー関数内でthisを使用すると、外側のスコープのthisを参照します。これにより、関数の内外でthisが一貫して参照できるため、特にイベントリスナーやコールバック関数で役立ちます。

callapplybindを使ったthisの制御

JavaScriptでは、callapplybindといった関数メソッドを使って、関数の実行時にthisの値を明示的に設定できます。

call: 関数を呼び出しながらthisの値を設定します。
apply: callと同様にthisの値を設定しながら関数を呼び出しますが、引数を配列として渡します。
bind: 関数にthisの値をバインドし、新しい関数を返します。

クラス内のthis

JavaScriptのクラスでは、メソッド内のthisはインスタンス化されたオブジェクトを参照します。ただし、イベントリスナーやコールバック関数内でクラスのメソッドを使う場合、thisの値が変わることがあります。その場合、アロー関数を使うか、bindメソッドでthisをバインドすることが役立ちます。

class MyClass {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, ${this.name}!`);
  }
}

const myInstance = new MyClass('Alice');
myInstance.greet(); // "Hello, Alice!"

const button = document.querySelector('button');
button.addEventListener('click', myInstance.greet); // "Hello, undefined!"
button.addEventListener('click', () => myInstance.greet()); // "Hello, Alice!"
button.addEventListener('click', myInstance.greet.bind(myInstance)); // "Hello, Alice!"

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?