JavaScript ES6中 class的本質

es6 - 代碼一

class Math {
    // 構造函數
    constructor(x,y) {
        this.x = x;
        this.y = y;
    }

    add() {
        return this.x + this.y;
    }
}


let math = new Math(1,2);
console.log(math.add());
上面的代碼和java C#等如此相似

es5 - 代碼二


// 一個數學計算的方法
function Math(x, y) {
    this.x = x;
    this.y = y;
}

// 在原型中添加 add方法, 其作用是返回兩個數的和
Math.prototype.add = function() {
    return this.x + this.y;
}

var math = new Math(1,2);
console.log(math.add())
上述代碼一代碼二其實是一樣的,es6的寫法明顯更爲清晰和簡單。

其實,es6中的class真正的本質是一個語法糖!

不信看下面的:大家猜猜這個Math是什麼類型的

class Math {
    // ...
}
console.log(typeof Math);
答案是 function

另外

Math === Math.prototype.constructor; // true

這個在 es5那段代碼(代碼二)中一樣適合

function Math(x, y) {
    this.x = x;
    this.y = y;
}
typeof Math; // "funtion"
Math === Math.prototype.constructor; // true 

放在一起:

es5

function Math(x, y) {
    this.x = x;
    this.y = y;
}

// 在原型中添加 add方法, 其作用是返回兩個數的和
Math.prototype.add = function () {
    return this.x + this.y;
}

var math = new Math(1,2);

console.log(typeof Math);  // "function"

console.log(Math === Math.prototype.constructor); // true

// 實例的隱式原型 === 方法的顯式原型
console.log(math.__proto__ === Math.prototype); // true

es6

class Math {
    // 構造函數
    constructor(x,y) {
        this.x = x;
        this.y = y;
    }

    add() {
        return this.x + this.y;
    }
}

let math = new Math(1,2);

console.log(typeof Math);  // "function" 

console.log(Math === Math.prototype.constructor); // true

// 實例的隱式原型 === 方法的顯式原型
console.log(math.__proto__ === Math.prototype); // true
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章