クラス
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
参考
何か指摘等ございましたら、コメントでお願いいたします。