ES6 Class 類

  • ES6中,class (類)作爲對象的模板被引入,可以通過 class 關鍵字定義類。
  • class 的本質是 function。
  • 它可以看作一個語法糖,讓對象原型的寫法更加清晰、更像面向對象編程的語法。

定義

類表達式可以爲匿名或命名。
// 匿名類
let Example = class {
    constructor(a) {
        this.a = a;
    }
}
// 命名類
let Example = class Example {
    constructor(a) {
        this.a = a;
    }
}


類聲明
class Example {
    constructor(a) {
        this.a = a;
    }
}


不可重複聲明。
class Example{}
class Example{}
// Uncaught SyntaxError: Identifier 'Example' has already been 
// declared
let Example1 = class{}
class Example{}
// Uncaught SyntaxError: Identifier 'Example' has already been 
// declared
 - 類定義不會被提升,這意味着,必須在訪問前對類進行定義,否則就會報錯。
 - 類中方法不需要 function 關鍵字。
 - 方法間不能加分號。
new Example(); 
class Example {}

類的主體

prototype屬性
ES6 中,prototype 仍舊存在,雖然可以直接自類中定義方法,但是其實方法還是定義在 prototype 上的。 覆蓋方法 / 初始化時添加方法

Example.prototype={
    //methods
}


添加方法
Object.assign(Example.prototype,{
    //methods
})


靜態屬性:class 本身的屬性,即直接定義在類內部的屬性( Class.propname ),不需要實例化。 ES6 中規定,Class 內部只有靜態方法,沒有靜態屬性。
class Example {
// 新提案
    static a = 2;
}
// 目前可行寫法
Example.b = 2;


公共屬性
class Example{}
Example.prototype.a = 2;


實例屬性:定義在實例對象( this )上的屬性。
class Example {
    a = 2;
    constructor () {
        console.log(this.a);
    }
}


name 屬性
返回跟在 class 後的類名(存在時)let Example=class Exam {
    constructor(a) {
        this.a = a;
    }
}
console.log(Example.name); // Exam
let Example=class {
    constructor(a) {
        this.a = a;
    }
}
console.log(Example.name); // Example

方法

constructor 方法是類的默認方法,創建類的實例化對象時被調用。
class Example{
    constructor(){
      console.log('我是constructor');
    }
}
new Example(); // 我是constructor


返回對象
class Test {
    constructor(){
        // 默認返回實例對象 this
    }
}
console.log(new Test() instanceof Test); // true
class Example {
    constructor(){
        // 指定返回對象
        return new Test();
    }
}
console.log(new Example() instanceof Example); // false


靜態方法
class Example{
    static sum(a, b) {
        console.log(a+b);
    }
}
Example.sum(1, 2); // 3


原型方法
class Example {
    sum(a, b) {
        console.log(a + b);
    }
}
let exam = new Example();
exam.sum(1, 2); // 3


實例方法
class Example {
    constructor() {
        this.sum = (a, b) => {
            console.log(a + b);
        }
    }
}

類的實例化

class 的實例化必須通過 new 關鍵字。
class Example {}
let exam1 = Example(); 
// Class constructor Example cannot be invoked without 'new'


共享原型對象
class Example {
    constructor(a, b) {
        this.a = a;
        this.b = b;
        console.log('Example');
    }
    sum() {
        return this.a + this.b;
    }
}
let exam1 = new Example(2, 1);
let exam2 = new Example(3, 1);
console.log(exam1._proto_ == exam2._proto_); // true
exam1._proto_.sub = function() {
    return this.a - this.b;
}
console.log(exam1.sub()); // 1
console.log(exam2.sub()); // 2

decorator 是一個函數,用來修改類的行爲,在代碼編譯時產生作用。

類修飾
一個參數target,指向類本身。
function testable(target) {
    target.isTestable = true;
}
@testable
class Example {}
Example.isTestable; // true


多個參數——嵌套實現
function testable(isTestable) {
    return function(target) {
        target.isTestable=isTestable;
    }
}
@testable(true)
class Example {}
Example.isTestable; // true
上面兩個例子添加的是靜態屬性,若要添加實例屬性,在類的 prototype 上操作即可。


方法修飾:3個參數:target(類的原型對象)、name(修飾的屬性名)、descriptor(該屬性的描述對象)。
class Example {
    @writable
    sum(a, b) {
        return a + b;
    }
}
function writable(target, name, descriptor) {
    descriptor.writable = false;
    return descriptor; // 必須返回
}


修飾器執行順序
由外向內進入,由內向外執行。
class Example {
    @logMethod(1)
    @logMthod(2)
    sum(a, b){
        return a + b;
    }
}
function logMethod(id) {
    console.log('evaluated logMethod'+id);
    return (target, name, desctiptor) => console.log('excuted         logMethod '+id);
}
// evaluated logMethod 1
// evaluated logMethod 2
// excuted logMethod 2
// excuted logMethod 1

封裝與繼承

getter / setter
定義
class Example{
    constructor(a, b) {
        this.a = a; // 實例化時調用 set 方法
        this.b = b;
    }
    get a(){
        console.log('getter');
        return this.a;
    }
    set a(a){
        console.log('setter');
        this.a = a; // 自身遞歸調用
    }
}
let exam = new Example(1,2); // 不斷輸出 setter ,最終導致 RangeError
class Example1{
    constructor(a, b) {
        this.a = a;
        this.b = b;
    }
    get a(){
        console.log('getter');
        return this._a;
    }
    set a(a){
        console.log('setter');
        this._a = a;
    }
}
let exam1 = new Example1(1,2); // 只輸出 setter , 不會調用 getter 方法
console.log(exam._a); // 1, 可以直接訪問


getter 不可單獨出現
class Example {
    constructor(a) {
        this.a = a; 
    }
    get a() {
        return this.a;
    }
}
let exam = new Example(1); // Uncaught TypeError: Cannot set property // a of #<Example> which has only a getter


getter 與 setter 必須同級出現
class Father {
    constructor(){}
    get a() {
        return this._a;
    }
}
class Child extends Father {
    constructor(){
        super();
    }
    set a(a) {
        this._a = a;
    }
}
let test = new Child();
test.a = 2;
console.log(test.a); // undefined
 
class Father1 {
    constructor(){}
    // 或者都放在子類中
    get a() {
        return this._a;
    }
    set a(a) {
        this._a = a;
    }
}
class Child1 extends Father1 {
    constructor(){
        super();
    }
}
let test1 = new Child1();
test1.a = 2;
console.log(test1.a); // 2

通過 extends 實現類的繼承。

class Child extends Father { ... }


子類 constructor 方法中必須有 super ,且必須出現在 this 之前。
class Father {
    constructor() {}
}
class Child extends Father {
    constructor() {}
    // or 
    // constructor(a) {
        // this.a = a;
        // super();
    // }
}
let test = new Child(); // Uncaught ReferenceError: Must call super 
// constructor in derived class before accessing 'this' or returning 
// from derived constructor


調用父類構造函數,只能出現在子類的構造函數。

class Father {
    test(){
        return 0;
    }
    static test1(){
        return 1;
    }
}
class Child extends Father {
    constructor(){
        super();
    }
}
class Child1 extends Father {
    test2() {
        super(); // Uncaught SyntaxError: 'super' keyword unexpected     
        // here
    }
}


調用父類方法, super 作爲對象,在普通方法中,指向父類的原型對象,在靜態方法中,指向父類
class Child2 extends Father {
    constructor(){
        super();
        // 調用父類普通方法
        console.log(super.test()); // 0
    }
    static test3(){
        // 調用父類靜態方法
        return super.test1+2;
    }
}
Child2.test3(); // 3


不可繼承常規對象。
var Father = {
    // ...
}
class Child extends Father {
     // ...
}
// Uncaught TypeError: Class extends value #<Object> is not a constructor or null
// 解決方案
Object.setPrototypeOf(Child.prototype, Father);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章