JavaScript-ES6中-class的本质

28次阅读

共计 1180 个字符,预计需要花费 3 分钟才能阅读完成。

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

正文完
 0