ES6 class extends


class Polygon {
    constructor(width, height) {
        console.log("first!");//调用静态方法时,constructor 并没有执行
        this.width = width;
        this.height = height;
        this.name = "Polygon";
    }

    //为属性添加 getter
    get area() {
        return this.square || this.width * this.height;
    }

    //为属性添加 setter
    set area(square) {
        this.square = square;
    }

    //实例方法
    sayName() {
        console.log(this.name);
        //this.hello();//静态方法不能直接在非静态方法中使用 this 关键字来访问
        this.constructor.hello();//可以使用 this.constructor.STATIC_METHOD_NAME()
        Polygon.hello();//还可以直接使用 CLASSNAME.STATIC_METHOD_NAME()
    }

    static hello() {
        console.log("hello." + this.name);//静态方法中可以使用 this 调用属性,会使用 constructor 中默认值
        //this.sayName();//但不可以使用 this 调用非静态方法,静态方法中,不可以调用实例方法
    }

    static say() {
        this.hello();//在同一个类中的一个静态方法调用另一个静态方法,你可以使用 this 关键字
    }
}

class Square extends Polygon{
    constructor(length) {
        super(length, length);
        this.name = "Square";
    }

    set area(square) { // 重名方法会覆盖
        this.square = square;
        this.width = this.height =  Math.sqrt(square);
    }
}

Polygon.say();
let a = new Polygon(2, 3);
a.sayName();
console.log(a.width, a.height, a.square, a.name);

Square.hello();
let b = new Square(5);
b.area = 16;
b.sayName();
console.log(b.width, b.height, b.square, b.name);
/*
hello.Polygon
first!
Polygon
hello.Polygon
hello.Polygon
2 3 undefined 'Polygon'
hello.Square
first!
Square
hello.Square
hello.Polygon
4 4 16 'Square'
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值