JavaScriptのES5とES6のクラスの作成と継承を1分で理解する

JavaScriptのオブジェクト指向と継承は、頻繁に使用されるメソッドとメソッドです。

1.クラスを作成する従来の方法(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(); // 调用自己的方法

2.ES6の新しいクラスの記述

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