ES6 新增class类定义对象类型
发布日期:2021-05-07 03:16:27 浏览次数:26 分类:精选文章

本文共 2283 字,大约阅读时间需要 7 分钟。

在ES2015之前,定义对象的类型,通常使用定义构造函数的方法和定义构造函数的原型对象的方法去定义。在ES2015中 新增了class类定义对象类型

class 类

//以前的方法 定义一个类型并定义方法function Person(name,age){      this.age = age;   this.name = name;}//在原型对象上添加方法Person.prototype.message = function(){       console.log(`${     this.name} is ${     this.age} years old`);}const person = new Person("li",18);console.log(person);person.message();

利用class简化代码,更加简洁,易懂

class Person{   //constructor 相当于构造函数,可以接收参数   constructor(name,age){          this.name = name;       this.age = age;   }//this 都是指向实例自己//在类里直接添加方法即可    message(){           console.log(`${     this.name} is ${     this.age} years old`);    }}const p = new Person("zhang",20);console.log(p);p.message();
静态成员 static:ES2015中新增添加静态方法的关键词static
  • 实例方法,构造函数生成实例对象上添加的方法

    静态方法,直接在构造函数上添加的方法(构造函数.直接添加)

class Person{   //constructor 相当于构造函数,可以接收参数   constructor(name,age){              this.name = name;           this.age = age;    }//this 都是指向实例自己//在类里直接添加方法即可  message(){          console.log(`${     this.name} is ${     this.age} years old`);   }//static 静态方法,将来是Person 打点调用此方法  static create(name,age){           console.log(this);      //静态方法中的this,不是指向实例对象的,而是指向类型整体       return new Person(name,age);       //将来生成person实例  }}//const p = new Person("zhang",20);//调用类型的静态方法const p = Person.create("lili",22);console.log(p);p.message();

需要注意的一点在↓↓↓

static create(name,age){       console.log(this);    //静态方法中的this,不是指向实例对象的,而是指向类型整体    return new Person(name,age);    //将来生成person实例}

上述代码中,this的指向不是实例对象,而是类型的整体。

类型的继承
  • 使用extend关键字继承父类,使用super()可以调用父类中的关键字,super.父类方法()引用、执行父类的方法。
class Person{     //constructor 相当于构造函数,可以接收参数    constructor(name,age){              this.name = name;           this.age = age;    }//this 都是指向实例自己//在类里直接添加方法即可  message(){         console.log(`${     this.name} is ${     this.age} years old`);   }//static 静态方法,将来是Person 打点调用此方法   static create(name,age){          console.log(this);       //静态方法中的this,不是指向实例对象的,而是指向类型整体       return new Person(name,age);       //将来生成person实例  }}    //继承class Student extends Person{      constructor(name,age,id){      super(name,age);//继承Person类    //设置自己单独的属性       this.id = id;        }   msg(){            super.message();//使用父类中的方法        console.log(`学号是 ${     this.id}`);    }}const s = new Student("lisa",20,001);s.msg();
上一篇:linux 软链接和硬链接
下一篇:gcc 与g++

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年04月15日 18时42分47秒