ES6精讲15-类的创建和继承

271 阅读1分钟

1.类的创建

ES5中类的创建

function Person(name,age) {
    this.name = name;
    this.age = age;
}
Person.prototype.sayName = function() {
    return this.name;
}
let p1 = new Person('小马哥',28);
console.log(p1); //{name: "小马哥", age: 28}

ES6中类的创建:

class Person {
    // 实例化的时候会立即被调用
    constructor(name, age) {
        this.name = name;
        this.age = age;
        this.love = "我一直在最温暖的地方等你";
    }
    //内部添加方法
    sayLove(){
        return this.love
    }
}

// 通过Object.assign()方法一次性向类中添加多个方法
Object.assign(Person.prototype, {
    sayName() {
        return this.name
    },
    sayAge() {
        return this.age
    }
})
let p1 = new Person('小马哥', 28);
console.log(p1); //{name: "小马哥", age: 28, love: "我一直在最温(prototype中也会有sayName,sayAge,sayLove方法)

2.类的继承

Animal为父类,Dog为子类

// 使用关键字 extends
class Animal{
    constructor(name,age) {
        this.name = name;
        this.age = age;
    }
    sayName(){
        return this.name;
    }
    sayAge(){
        return this.age;
    }
}

 class Dog extends Animal{
    constructor(name,age,color) {
        super(name,age);
        // Animal.call(this,name,age);
        this.color = color;
    }
    // 子类自己的方法
    sayColor(){
        return `${this.name}${this.age}岁了,它的颜色是${this.color}`
    }
    // 重写父类的方法
    sayName(){
        return this.name + super.sayAge() + this.color;
    }
}
let d1 = new Dog('小黄',28,'red');
console.log(d1.sayColor()); //小黄是28岁了,它的颜色是red
console.log(d1.sayName());  //小黄28red
  • super起到的作用和Animal.call方法类似
  • 在子类中,通过super+方法名可以调用父类的方法(🌵上面例子中super.sayAge()就是)

🤔思考题:如何让多个类 混入到一个类中????

juejin.cn/post/684490…