less than 1 minute read

学んだこと

クラスにメソッドを追加する

  • C++や C#でのクラスメソッドの書き方とほぼ一緒
    • クラス内に関数を宣言するだけ
class Person {
  name: string;

  constructor(initName: string){
    this.name = initName
  }

  // これがクラスメソッド
  greeting(){
    console.log("hello")
  }
}

this の意味合い

  • クラスメソッド内の this は呼び出し先で異なる
  • コンストラクタで呼ばれた this は自分のクラスを指す
class Person {
  name: string;

  constructor(initName: string){
    this.name = initName
  }

  greeting(){
    // ここのthisはPerson
    console.log(this.name)
  }
}

const quill = new Person("Quill");
const anotherQuill: {
  anotherGreeting: () => void;
}

// この場合のthisはanotherQuill
// anotherQuillにはnameがないのでundefinedになる
anotherQuill.anotherGreeting();

this を正しく使いたい場合

  • 呼び出したいクラスメソッドの第一引数に this を追加する
class Person {
  name: string;

  constructor(initName: string){
    this.name = initName
  }

  greeting(this: {name: string}){
    console.log(this.name)
  }
}

const quill = new Person("Quill");
const anotherQuill: {
  anotherGreeting: () => void;
}

// ここでエラーになる
anotherQuill.anotherGreeting();

クラスを型として扱う

class Person {
  name: string;

  constructor(initName: string){
    this.name = initName
  }

  // thisにPersonを設定する
  greeting(this: Person){
    console.log(this.name)
  }
}

const quill = new Person("Quill");
const anotherQuill: {
  greeting: quill.greeting
}

anotherQuill.greeting();

アクセス指定子も使える

  • public や private も使うことができる
  • public
    • どこからでもクラスの関数、変数にアクセスできる
  • private
    • クラスの関数、変数にアクセスできない

クラスの初期化処理を省略

  • コンストラクタの引数に初期化するクラス内変数を設定することで初期化処理を行うことができる。
class Person {
  name: string;

  constructor(public name: string){
  }

  // thisにPersonを設定する
  greeting(this: Person){
    console.log(this.name)
  }
}

const quill = new Person("Quill");
const anotherQuill: {
  greeting: quill.greeting
}

anotherQuill.greeting();