一分钟看懂JavaScript里的ES5和ES6中类的创建和继承

JavaScript 的面向对象和继承,是经常用到的方式和方法。

一、传统方法写类(ES5)

// 1. 构造函数
let Person = function({name,age,height}={}){
    this.name = name ;
    this.age = age ;
    this.height = height ;
};
// 2. 原型添加方法
Person.prototype.showName = function(){
    console.info(`${this.name} 今年 ${this.age} 岁`);
};

// 3. 创建子类,并继承
let Teacher = function({name,age,height,school}={}){
    Person.call(this,{
        name:name,
        age:age,
        height:height
    });
    this.school = school ;
};
// 继承父类方法
// 方式一:原型链继承
/* for(let item in Person.prototype ){
            Teacher.prototype[item] = Person.prototype[item];
        }*/

// 方式二:Object.create()
// Teacher.prototype = Object.create( Person.prototype  );

// 方式三:调用构造函数继承
Teacher.prototype = new Person();

// 子类自己的方法
Teacher.prototype.showSchool = function(){
    console.info(`我来自 ${this.school}`);
};


// 4. 创建对象
let zhangsan = new Teacher({
    name : "张三",
    age : 29 ,
    height: "180cm",
    school:"重庆工程学院"
});
zhangsan.showName();   // 调用父类方法
zhangsan.showSchool(); // 调用自己的方法

二、ES6 新增 class 写法

class Person{
    //1. 构造器:内部写属性
    constructor({name,age,height}){
        this.name = name ;
        this.age = age ;
        this.height = height ;
    }
    //2. 添加方法
    showName(){
       console.info(`${this.name} 今年 ${this.age} 岁`);
    }
}
// extends 继承
class Teacher extends Person{
    constructor({name,age,height,school}={}){
        // 继承属性。方法会通过 extends 自动继承
        super({
            name:name,
            age:age,
            height:height
        });
        this.school = school ;
    }

    //3. 添加子类自己的方法
    showSchool(){
        console.info(`我来自 ${this.school}`);
    }
}

// 4. 创建对象
let zhangsan = new Teacher({
    name : "张三",
    age : 29 ,
    height: "180cm",
    school:"重庆工程学院"
});
zhangsan.showName();   // 调用父类方法
zhangsan.showSchool(); // 调用自己的方法

注:构造函数的参数使用了对象结构的写法。对于 ES6 的解构,参考这篇文章 一文看懂 ES6 解构赋值

ES6 太方便了,是时候拥抱 ES6 了。

猜你喜欢

转载自blog.csdn.net/weixin_42703239/article/details/108088741