js es6語法 class類 class繼承 super關鍵字


一, 類的由來

es6提供了一個新語法就是class

二, class聲明一個類

// 聲明一個類
class Piont{ // Piont就是一個類  

}

1, 添加屬性和方法

class Piont {
    // 構造函數
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
	// 方法
    run(){
       console.log(1);
    }
}

2, 使用方式

var p = new Piont('劉德華',30);
p.run();
console.log(p.name);

3, 方法的寫入

run(){
    console.log(1);
}

對象調用的屬性和方法叫做成員屬性和方法,有類直接調用的屬性和方法叫靜態屬性和方法

靜態的屬性指的是Class本身不是定義在實列對象上的屬性

class Foo {

}

Foo.pop = 1; // 給Foo這個類定義了一個靜態屬性
console.log(Foo.pop);

4, 內部添加靜態屬性

class Po{
static myP = 100; // 靜態屬性
constructor(){
    console.log(Po.myP);
}
}

var p1 = new Po();
p1.constructor; // 調用

5, 添加靜態方法

class Foo{
    static po = 100; // 
    static classMethod(){
        return 'hello';
    }
}

6, this和方法重名

class Foo {
    static bar() {
        this.baz()
    }
    static baz() {
        console.log('hello');
    }
    baz() {
        console.log('world');
    }
}

Foo.bar();
var f = new Foo();
f.baz();

7, 父類的靜態方法可以被子類繼承

class Foo {
static classMethod() {
    return 'hello';
}
}
// 子類繼承父類
class Bar extends Foo { // 子類繼承父類

}
console.log(Bar.classMethod());

8, class繼承

Class可以通過extends關鍵字實現繼承,這比ES5通過修改原型鏈實現繼承

class Point{

}
// 子類繼承父類
class ColorPoint extends Point{

}

在ColorPoint內加上代碼

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}
// 在ColorPoint內加上代碼
class ColorPoint extends Point {
    constructor(x, y, color) {
        //  this.color = color; // 錯誤
        super(x, y); // 調用父類的constructor(x, y)
        this.color = color; //  正確的
    }

    toString() {
        return this.color + ' ' + super.toString;
        toString()
    }
}

let cp = new ColorPoint(20, 30, 'green');

console.log(cp instanceof ColorPoint);// true
console.log(cp instanceof Point); //  true 

console.log(cp.x, cp.y, cp.color);

9, super關鍵字

既可以當做函數使用,也可以當做對象使用

當做函數使用的時候,代表的是父類的構造函數,es6要求,子類的構造函數必須執行一些super

class A{
    constructor(){
        console.log(new.target.name);
    }
}

class B extends A{
    constructor(){
        super();// 代表的是父類的構造函數 但是返回的是子類的實列,內部的this指向的是子類的實列
        // 相當於
        // A.prototype.constructor.call(this);
    }
}

console.log(new A()); //A
console.log(new B()); //B

super作為對象使用,在普通方法中,指向父類的原型對象,在靜態方法中,指向的是父類

class A{
    p(){
        return 2;
    }
}
// 繼承
class B extends A {

    constructor(){
        super();
        console.log(super.p()); // 2  
    }
}

let b = new B();

由於super指向父類的原型對象,所以定義在父類實列上的方法或者屬性,是無法通過super調用

class A {
    constructor() {
        this.p = 2;
    }
}
// 繼承
class B extends A {
    get m() {
        return super.p;
    }
}

let b = new B();
console.log(b.m);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM