Es6 的語法糖,簡化了上一篇的寫法,讓程式碼更好閱讀
這邊改寫前一篇介紹過的例子
Before:
/*function Person(name,sex,age){
console.log(this); // {}
this.name = name;
this.sex = sex;
this.age = age;
}
Person.prototype.sayHi= function(){
console.log(this.name+" says Hi");
}*/
After:
class Person{
constructor(name,sex,age){
this.name = name;
this.sex = sex;
this.age = age;
}
sayHi(){
console.log(this.name+" says Hi");
}
}
let Helen = new Person("Helen","Female",24);
console.log(Helen)
let Daniel = new Person("Daniel","Male",23);
console.log(Daniel);
console.log(Helen.sayHi == Daniel.sayHi);
Helen 和 Daniel 都從同一個 prototype 去繼承 sayHi()
當我們要建立一個新的 function,並和 Person 共用參數時
Before:
/*function Student(name,sex,age,height,weight){
Person.call(this,name,sex,age);
this.height;
this.weight;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.study = function(){
console.log("I am studying")
}
let Daniel = new Student("Daniel","Male",23,172,56);
console.log(Daniel);
Daniel.sayHi(); // Daniel says Hi
Daniel.study(); // I am studying*/
After:
使用 extends 繼承 Person,super 是集合的概念(和離散數學有關)
class Person{
constructor(name,sex,age){
this.name = name;
this.sex = sex;
this.age = age;
}
sayHi(){
console.log(this.name+" says Hi");
}
}
class Student extends Person{
constructor(name,sex,age,height,weight) {
super(name,sex,age);
this.height = height;
this.weight = weight;
}
study(){
console.log("I am studying")
}
}
let Helen = new Student("Helen","Female",24,160,56);
console.log(Helen);
Helen.sayHi(); // Helen says Hi
Helen.study(); // I am studying
此時可以看到 Helen 的 prototype 裡不但有 study(),也繼承了 Person 裡 prototype 的 sayHi()
Static Properties and Methods 不是屬於 class 內所做出來的 object,而是屬於 class,任何 Properties and Methods 只要設成 static,他們就會屬於 class。
以計算圓面積和周長的例子來看,
Before:
/*
class Circle{
constructor(radius){
this.radius = radius;
}
getArea(){
return this.radius * this.radius * 3.14;
}
getPerimeter(){
return 2 * 3.14 * this.radius;
}
}
let circle1 = new Circle(5);
console.log(circle1); // 78.5
*/
因為 pi 是固定的,我們其實不需要在每個 function 都寫上 3.14,這時候可以使用 static,讓那些固定不變的 property 或 method 屬於 class。
After:
class Circle{
static pi = 3.14;
constructor(radius){
this.radius = radius;
}
getArea(){
return this.radius * this.radius * Circle.pi;
}
getPerimeter(){
return 2 * Circle.pi * this.radius;
}
static getAreaFormula(){
console.log("r * r * 3.14")
}
}
Circle.getAreaFormula(); // r*r*3.14
let circle1 = new Circle(10);
console.log(circle1.getArea()); // 314