[JS] JavaScript 類別(Class)
function constructor
有 hoisting 的情況,所以可以寫再後面但在前面使用;但是 class constructor 沒有 hoisting 的情況 ,所有使用該 class constructor
的程式,必須放在 class constructor 後面。
ES6 Class Playground @ jsfiddle
keywords: class
, constructor(data)
建立 Constructor
傳統 function constructor
過去使用 function constructor
來建構物件,並且搭配 prototype 來建議物件可使用的方法:
// 過去使用 function constructor
let Person = function (data) {
this.name = data.name;
this.age = data.age;
let profile = `${this.name}(${this.age})`; // 無法在實例中使用
};
Person.prototype.greet = function () {
console.log(`Hello ${this.name}, your age is ${this.age}`);
};
let Aaron = new Person({ name: 'Aaron', age: 28 });
let Jackson = new Person({ name: 'Jackson', age: 24 });
console.log(Aaron); // Person {name: "Aaron", age: 28}
在實例中取用不存在的變數時會得到
undefined
。
ES6 Class
在 ES6 中可使用關鍵字 class
和 constructor(self)
:
// 在 ES6 中可以透過 class 來建立 constructor
class Person {
constructor(data) {
this.name = data.name;
this.age = data.age;
}
}
let Aaron = new Person({ name: 'Aaron', age: 28 });
let Jackson = new Person({ name: 'Jackson', age: 24 });
console.log(Aaron); // Person {name: "Aaron", age: 28}
設定預設值:
// 同樣可以透過 object destructuring 來做到設定預設值
class Person {
constructor({ name, age = 18 } = {}) {
this.name = name;
this.age = age;
}
}
let Aaron = new Person({ name: 'Aaron' });
let Jackson = new Person({ name: 'Jackson', age: 24 });
console.log(Aaron); // Person {name: "Aaron", age: 18}
console.log(Jackson); // Person {name: "Jackson", age: 24}
在
class
中只能使用方法(function),不能直接代入資料。
Prototype method(原型方法)
原型方法(prototype method)指的是這些方法是建立來讓該類別的實例(instance)使用的。直接在建構式(constructor)中建立函式就是原型方法:
class Student {
constructor(firstName, lastName) {
// this 指稱的是所建立的 instance
this.firstName = firstName;
this.lastName = lastName;
}
// 原型方法
getName() {
// this 指稱的是所建立的 instance
return `${this.firstName} ${this.lastName}`;
}
}
// 類別的實力可以直接使用原型方法
aaron = new Student('Aaron', 'Chen');
console.log(aaron.getName()); // Aaron Chen
Static method(靜態方法)
keywords: static
static method 只存在 class 中,不能被 instance 所提取,只能透過指稱到該 class 才能使用該方法,可以透過 static
這個關鍵字來建立 static method:
靜態方法(static method)指的是該方法只能用在該 class 上,而不能用在 instance 上。
第一種方式:在 static 中使用 this
在 static
中使用 this
,在使用 static method 時搭配 call
來指定 this
的對象:
// 呼叫靜態方法的第一種方式
class Bird {
constructor({ color = 'red' } = {}) {
this.color = color;
}
// 使用 static 以建立 static method,裡面用 this
static changeColor(color) {
// this 原本指稱的是所建立的 Bird 這個 Class
// 但在呼叫這個方法時,使用了 call() 把 this 改成了指定的 instance
this.color = color;
}
}
let redBird = new Bird();
console.log(redBird.color); // red
// redBird.changeColor('blue') // redBird.changeColor is not a function
Bird.changeColor.call(redBird, 'blue');
console.log(redBird.color); // blue