美文网首页
JavaScript ES6中 class的本质

JavaScript ES6中 class的本质

作者: 邢走在云端 | 来源:发表于2019-10-27 21:34 被阅读0次

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

相关文章

  • JavaScript ES6中 class的本质

    es6 - 代码一 上面的代码和java C#等如此相似 es5 - 代码二 上述代码一和代码二其实是一样的,e...

  • ES6 class 静态属性和私有方法

      ES6中新增了class的定义方法,可以说是对JavaScript这门语言的极大丰富。虽然其本质上还是对象,但...

  • ES6 class 静态属性和私有方法

    ES6中新增了class的定义方法,可以说是对JavaScript这门语言的极大丰富。虽然其本质上还是对象,但是对...

  • ES6 中 class 与构造函数的关系

    ES6 中 class 与构造函数的关系class 为 构造函数的语法糖,即 class 的本质是 构造函数。c...

  • Day2. JSX核心语法一, 跟着Demo入门JSX

    一. Javascript类的定义 JS语法补充 ES5中定义类 class ES6开始才有的关键字 ES6中通过...

  • class继承

    class继承是从ES6开始正式被引入到JavaScript中。class的目的就是让定义类更简单。 用函数实现 ...

  • 原型与原型链

    JavaScript中除了基本类型外的数据类型,都是对象。但是由于其没有 类(class,ES6引入了class)...

  • 原型与原型链

    JavaScript中除了基本类型外的数据类型,都是对象。但是由于其没有 类(class,ES6引入了class,...

  • 浅析JavaScript中的原型链与继承

    在JavaScript中,ES6之前不存在class,所以JavaScript的继承是基于原型链实现的。每一个实例...

  • typescript之类

    类 类就是面向对象编程,javascript基于原型的方法来实现类,es6之后引入class关键字,本质上虽然还是...

网友评论

      本文标题:JavaScript ES6中 class的本质

      本文链接:https://www.haomeiwen.com/subject/onvmvctx.html