LoginSignup
0
1

More than 3 years have passed since last update.

【備忘録】クラス【TypeScript】

Last updated at Posted at 2021-01-02

クラス

TypeScript,JavaScript 初学者が関数のクラスについて勉強したのでメモを残す。

クラスの特徴

  • 下記の例を読んでみる。
class Person {
  constructor(name) {
    this.name = name;
  }
  static sayName = () => {
    console.log("私は${this.name}です。");
  };
  static explain = () => {
    cosole.log("${this.name}は人間です");
  };
}

class Man extends Person {
  construcror(name) {
    super(name);
  }
  sayGender = () => {
    console.log("${this.name}は男です。");
  };
}
  • メンバーメソッドはアロー関数でも OK
  • JavaScript にとってクラスとはコンストラクタ関数である
> class sampleClass {
... constructor(name){
..... this.name = name
..... }
... }
undefined
> typeof sampleClass
'function'

sampleClassの型が関数であることがわかる。(TypeScriptがプロトタイプベースであるため。)

TypeScript はプロトタイプベース(⇆クラスベース)

  • クラスベース
    • 継承元がクラス
  • オブジェクトベース

    • 継承元がオブジェクト(プロトタイ)
    • あらゆるオブジェクトがなんらかのプロトタイプを継承する(プロトタイプチェーン
    • プロトタイプチェーンは空オブジェクト{}を経てnullに行き着く
    > const yasushinari = new Man("yasushi");
    >
    > yasushinari.__proto__
    Man{}
    > yasushinari.__proto__.__proto__
    Person{}
    > yasushinari.__proto__.__proto__.__proto__
    {}
    > yasushinari.__proto__.__proto__.__proto__.__proto__
    null
    
    • クラス構文をプロトタイプベースで書き直すと以下のようになる
  function Person(name) {
    this.name = name;
    this.sayName = function () {
      console.log("私は${this.name}です。");
    };

    return this;
  }

  Person.explain(name) {
    cosole.log("${this.name}は人間です");
  }

  function Man(name) {
    Person.call(this, name);
    this..sayGender(name) {
      console.log("${this.name}は男です。");
    }

    return this;
  }

  Man.prototype.__proto___ = Man.prototype;

なぜプロトタイプベースなのか(プロトタイプベースの良さ)

  • クラスベースより軽量に実装可能。
  • プロトタイプのメソッドを編集追加削除が容易にできる。
  class Person {
    constructor(name) {
      this.name = name;
    }

    sayName = (name) => {
      console.log(`My name is ${this.name}.`);
    };
  }

  const yasushi = new Person("yasushi");

  yasushi.sayName(); // My name is yasushi.

  // メソッドを編集
  yasushi.sayName = function () {
    return console.log(`I'm ${this.name}.`);
  };
  yasushi.sayName(); // I'm yasushi.

  // メソッドの追加
  yasushi.sayHello = function () {
    return console.log("Hello!");
  };
  yasushi.sayHello(); // Hello!

  // メソッドの削除
  delete yasushi.sayName();
  yasushi.sayName(); // TypeError: yasushi.sayName is not a function

参考

何か指摘等ございましたら、コメントでお願いいたします。

0
1
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
1