LoginSignup
0
0

More than 3 years have passed since last update.

関数とオブジェクトメソッドでは、thisの参照先は異なる

Posted at

はじめに

オブジェクトメソッドと関数でthisを使用したときに、参照先が異なる。

  • オブジェクトメソッド
    this ⇒ 呼び出し元オブジェクト

  • 関数
    this => グローバルオブジェクト

実例

説明だけだと、イメージしずらいのでコードを交えて確認していきます。

オブジェクトメソッドの場合

const car = {
    name: 'ベンツ',
    drive: function() {
        console.log(this.name + 'を運転する。');
    }
}

car.drive();

出力結果

ベンツを運転する。

関数の場合

window.name = 'ランボルギーニ';

const car = {
    name: 'ベンツ',
    drive: function() {
        console.log(this.name + 'を運転する。');
        sell();
    }
}

function sell() {
    console.log(this.name + 'を売りたい。');
}

car.drive();

出力結果

ベンツを運転する。
ランボルギーニを売りたい。

おまけ

オブジェクトの中にオブジェクトメソッドを追加した場合

window.name = 'ランボルギーニ';

const car = {
    name: 'ベンツ',
    drive: function() {
        console.log(this.name + 'を運転する。');
        sell();

        const car = {
            name: 'プリウス',
            drive: function() {
                console.log(this.name + 'を運転する。');
                sell();
            }
        }
        car.drive();
    }
}

function sell() {
    console.log(this.name + 'を売りたい');
}

car.drive();

出力結果

ベンツを運転する。
ランボルギーニを売りたい。
プリウスを運転する。
ランボルギーニを売りたい。
0
0
2

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