ES6-面向对象与继承

2022-07-09  本文已影响0人  测试探索

一:类

class Point{
    //构造函数
    constructor(x,y) {
        this.x = x;
        this.y = y;
    }

    toString(){
        return '点的位置:(' + this.x + ',' + this.y +  ')'
    }
}

let p = new Point(1,2);

console.log(p.toString());
image.png

二、静态方法

image.png
class MyDate{
    static validateMonth(month){
        month = Number.parseInt(month);
        return month >= 1 && month <=12;
    }
}

console.log(MyDate.validateMonth(12));
image.png

三、继承

3-1:继承的使用
image.png

class Animal {
    constructor(name,age) {
        this.name = name;
        this.age = age;
    }

    eat(){
        return "Food";

    }
    showInfo(){
        console.log("动物的信息:名称" + this.name + ",年龄" + this.age);
    }

}

//继承
class Cat extends Animal {
    constructor(name,age,color) {
        super(name,age);
        this.color = color;
    }

}

let cat = new Cat('小黑',3,'black');
cat.showInfo();

let animal = new Animal("小黄",5);
animal.showInfo();

let food = animal.eat();
console.log(food);
image.png
3-2:重写父类方法demo1

class Animal {
    constructor(name,age) {
        this.name = name;
        this.age = age;
    }

    eat(){
        return "Food";

    }
    showInfo(){
        console.log("动物的信息:名称" + this.name + ",年龄" + this.age);
    }

}

//继承
class Cat extends Animal {
    constructor(name,age,color) {
        super(name,age);
        this.color = color;
    }

//   重写showInfo方法
    showInfo(){
        console.log("毛的信息:名称" + this.name + ",年龄" + this.age + ",毛色" + this.color);
    }

}

let cat = new Cat('小黑',3,'black');
cat.showInfo();

let animal = new Animal("小黄",5);
animal.showInfo();

let food = animal.eat();
console.log(food);
image.png

demo2


class Animal {
    constructor(name,age) {
        this.name = name;
        this.age = age;
    }

    eat(){
        return "Food";

    }
    showInfo(){
        console.log("动物的信息:名称" + this.name + ",年龄" + this.age);
    }

}

//继承
class Cat extends Animal {
    constructor(name,age,color) {
        super(name,age);
        this.color = color;
    }

    eat() {
        //调用父类的方法
        let result =  super.eat();
        console.log("来自父类:",result);
        return result + "fish"

    }

//   重写showInfo方法
    showInfo(){
        console.log("毛的信息:名称" + this.name + ",年龄" + this.age + ",毛色" + this.color);
    }

}

let cat = new Cat('小黑',3,'black');
cat.showInfo();
let foods = cat.eat();
console.log(foods);

let animal = new Animal("小黄",5);
animal.showInfo();

let food = animal.eat();
console.log(food);
image.png
上一篇下一篇

猜你喜欢

热点阅读