前一篇章節向大家帶來了 OOP 的概念,本篇開始將針對 Class 的實作開始講解並介紹: 繼承、封裝、多型等重要概念與實現。
屬性和方法
class
class 是宣告類別名稱的關鍵字。
constructor()
Js/Ts 利用 constructor() 定義好類別實體化的那一刻要做什麼樣的初始化設定。
constructor() 也可以有一個很專業的名詞 : 建立者函數。
new
宣告完類別以後還沒有結束! 我們需要使用 new 將物件實體化。
剛開始學習 JavaScript 時,常常會出現 這什麼鬼 Moment , new 這個關鍵字也不例外。
class Animal {
constructor(name) {
this.name = name;
}
sayHi() {
return `My name is ${this.name}`;
}
}
let a = new Animal('Jack');
console.log(a.sayHi()); // My name is Jack
類別的繼承
extends
super()
存取器
getter
定義 getter 函式作為取得參數的唯一管道 。
setter
定義 setter 函式作為更改參數的唯一管道 。
為了讓讀者了解 getter, setter 的意義,筆者在這邊將 name 資料成員設為私用變數。
class Cat extends Animal {
constructor(name) {
super(name); // 呼叫父類別的 constructor(name)
console.log(this.name);
}
sayHi() {
return 'Meow, ' + super.sayHi(); // 呼叫父類別的 sayHi()
}
}
let c = new Cat('Tom'); // Tom
console.log(c.sayHi()); // Meow, My name is Tom
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
get Name() {
return this.name;
}
set Name(value) {
this.name = value;
console.log("setter: " + this.name);
}
}
let a = new Animal("Kitty");
console.log(a.Name); // Kitty
a.Name = "Tom"; // setter: Tom
console.log(a.Name); // Tom
error: TS2341 [ERROR]: Property 'name' is private and only accessible within class 'Animal'.
class Animal {
static isAnimal(a) {
return a instanceof Animal;
}
}
let a = new Animal('Jack');
Animal.isAnimal(a); // true
a.isAnimal(a); // TypeError: a.isAnimal is not a function
class Animal {
public name: string;
protected constructor(name: string) {
this.name = name;
}
sayHi() {
console.log(this.name);
}
}
class Cat extends Animal {
protected birthday: number;
constructor(name: string) {
super(name);
this.birthday = 8;
}
say() {
console.log(this.birthday);
}
}
let a = new Cat("Jack");
a.say();
class Animal {
public name: string;
protected constructor(name: string) {
this.name = name;
}
sayHi() {
console.log(this.name);
}
}
class Cat extends Animal {
protected birthday: number;
constructor(name: string) {
super(name);
this.birthday = 8;
}
say() {
console.log(this.birthday);
}
}
let a = new Cat("Jack");
a.sayHi();
let a = new Cat("Jack");
a.sayHi();
class Animal {
public name: string;
protected constructor(name: string) {
this.name = name;
}
sayHi() {
console.log(this.name);
}
}
class Cat extends Animal {
protected birthday: number;
constructor(name: string) {
super(name);
this.birthday = 8;
}
say() {
console.log(this.birthday);
}
}
let a = new Cat("Jack");
a.sayHi();
a.birthday;
error: TS2445 [ERROR]: Property 'birthday' is protected and only accessible within class 'Cat' and its subclasses.
a.birthday;