JavaScriptでthisっていつ使うの?

使うシーンは主に2パターン

  1. Object内の変数を呼び出すときthisを使う

  2. Objectそのものを返す(関数の戻り値をObjectそのものにしたい)ときにthisを使う

1. Object内の変数を呼び出すときthisを使う

オブジェクトのスコープ内の変数を呼び出すパターン

const person = {
  name: '高橋',
  age: 24,
  
  getName() {
        // personオブジェクト内の変数 name を呼び出したいので、this.name とする
    console.log(this.name);
  },

  getAge() {
    // ageが見つからないため age is not defined のエラーとなる
    console.log(age);
  }
};

person.getName(); // -> 高橋が出力される
person.getAge(); // -> age is not defined となる

オブジェクト外の変数を呼び出すパターン

const age = 42 // グローバル変数

const person = {
  name: '高橋',
  age: 24,
  
  getName() {
        // personオブジェクト内の変数 name を呼び出したいので、this.name とする
    console.log(this.name);
  },

  getAge() {
    // グローバル変数の age が呼び出される
    console.log(age);
  }
};

person.getName(); // -> 高橋が出力される
person.getAge(); // -> 42が出力される

2. Objectそのものを返す(関数の戻り値をObjectそのものにしたい)ときにthisを使う

Object内で定義した関数に return this を記述する
この記述によりメソッドチェーンで関数を呼び出せるようになる

const age = 42;

const person = {
  name: '高橋',
  age: 24,

  getName() {
    console.log(this.name); // -> 高橋が出力される
    return this; // <- この this は personオブジェクトと同義
  },

  getAge() {
    console.log(this.age); // -> 24が出力される
    return this; // <-  この this は personオブジェクトと同義
  },
};

person.getName().getAge(); // -> -> 高橋 と 24 が出力される

NGパターン

const age = 42;

const person = {
  name: '高橋',
  age: 24,

  getName() {
    console.log(this.name);
  },

  getAge() {
    console.log(this.age);
  },
};

// .getAge()関数が読み取れないため、高橋は出力された後に下記のエラーになる
// Uncaught TypeError: Cannot read properties of undefined (reading 'getAge')
person.getName().getAge();

この記事が気に入ったらサポートをしてみませんか?