2020-08-17

js 中的class

类声明

需要声明一个类,需要使用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);

即可完成对类的使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值