天天看點

js 中的class一些解釋類聲明constructorstatic關于嚴格模式extendssuper

js 的calss

由于存在轉換器這種神器,是以代碼能直接轉換為es5,用es6的文法寫。

一些解釋

js的calss僅僅為一個文法糖,是在原先構造函數的基礎上出現的class,僅僅如此。是以使用構造函數構造類,或者使用class文法糖構造類都是相同的。具體還是使用prototype和this來進行模拟類。

重點在于構造函數,使用的是構造函數來模拟類。

類聲明

需要聲明一個類,需要使用class

class Rectangle {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
}           
和函數聲明的最大的差別在于,類聲明,不會出現聲明提前,函數聲明會出現聲明提前,這是兩者最大的差別。

在上方中,聲明類以後,建立一個對象。

let rectAngle = new Rectangle           

該對象具有constructor方法。

匿名類

和匿名函數類似,類依舊可以進行匿名聲明

let Rectangle = class {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
}           
在類表達式中,同樣會出現類聲明提升的問題。

constructor

為一個構造函數,用于初始化class并建立一個對象

即為原先學習的構造函數,函數為對象,對象為函數。
class Rectangle {
    // 構造函數
    constructor(height, width) {
        this.height = height;
        this.width = width;
    };
    // get 方法即調用将會傳回的值
    get area() {
        return this.calcArea();
    };
    // 定義calcArea函數
    calcArea() {
        return this.height * this.width;
    }
}           

上方定義了一個類如果需要使用

const square = new Rectangle();
console.log(square.area);           

即可完成對類的使用。

static

為一個靜态方法,該靜态new出的來的對象不能進行使用。

常常用于工具函數的書寫
class Point {
    constructor(x, y){
        this.x = x;
        this.y = y;
    };

    static distance(a, b){
        const dx = a.x - b.x;
        const dy = a.y - b.y;
        return Math.hypot(dx, dy);    // 畢達哥拉斯定理
    }
}
// 使用
const p1 = new Point(5,5);
const p2 = new Point(10,10);
console.log(Point.distance(p1,p2));           

關于嚴格模式

由于js存在嚴格模式,并且上面的内容在嚴格模式下執行,如果該對象沒有this的值,将不會傳回其本身。

傳統的使用prototype将會傳回其本身,因為傳統的不在嚴格模式下執行。

extends

使用extends建立子類

class Animal {
    constructor(name) {
        this.name = name;
    }

    speak() {    // 由于是在類中定義,function關鍵字可以省去
        console.log(this.name);
    }
}
// 建立DOg父類
class Dog extends Animal {
    speak() {
        console.log(this.name);
    }
}

let d = new Dog();
d.name = "ming"
d.speak();           

類不可繼承沒有構造函數的對象

如果一個對象沒有構造函數,将不能進行繼承。

請使用

Object.create()           

進行建立給予對象的新對象

const a = {

};

const b = Object.create(a);    // 建立基于原型a的對象           

super

使用super調用超類

class Cat {
    constructor(name) {
        this.name = name;
    }

    speak() {
        console.log();
    };
}  

class Lion extends Cat {
    speak() {
        super.speak();
    }
}

           

即使用super調用超類

繼續閱讀