js 中的class

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;
    }
}

在类表达式中,同样会出现类声明提升的问题。

原文链接

猜你喜欢

转载自blog.csdn.net/weixin_40581617/article/details/82839268