ES6 Class
基本用法:
class human {
constructor(height, weight){
this.height = height;
this.weight = weight;
}
get getHeight() {
return this.height;
}
}
const alice = new human(178, 67);
console.log(alice);
// 178constructor 用來將傳進new class 的參數賦予給class內的變數。
用this.height來將傳進來的height讓class內可以使用。
Static
class human {
constructor(height, weight){
this.height = height;
this.weight = weight;
}
static fly() {
console.log(this)
console.log(new this(12,12));
}
}
human.fly();static 方法的this會是還沒有new之前的class,所以也沒辦法存取到this.height
console.log(this) 會是 [Function: human]
class 均為嚴格模式執行 (no autoboxing)
繼承父 class
如果class內 function名稱相同會繼承,但也可以直接在子類別覆蓋
class 換成 function
不同class 傳遞參數
假設其上層的 js
呼叫父類別方法
繼承
或是
Last updated
Was this helpful?