首页 > 技术文章 > js面向对象编程

lyzz1314 2021-06-02 19:11 原文

基本概念:原型链、继承

class Person {
  // 这里定义固定的属性,该属性定义在每一个new出来的对象上面
  canSpeak = true;
  canSleep = true;
  toFuck = ()=>{
    // 箭头函数中的this会自动向外层寻找,外层的this指向的就是该实例(此处使用function则不行)
    if( this.canSleep == true ){
      this.speak();
    }else{
      return 
    }
  };
  // static关键字的使用使得defaultProps定义在了该类的原型对象上面,而不是存在于实例对象上,注意与上面的属性定义方式相区分
  static defaultProps = {
    sex: '男',
    age: 18
  }
  // 定义构造器,传入参数
  constructor(name,age){
    this.name = name;
    this.age = age;
  }
  // 思考: speak对象放在了哪里? ----类的原型对象(prototype)上(实例对象上面没有),供实例使用。
  speak(){
    console.log(`I am ${this.name}, ${this.age} years old.`);
  }

}

// 继承
class Student extends Person {
  // constructor也可以不写,如果写了就必须有super来继承父亲的属性
  constructor(name,age,grade){
    super(name,age); // 如果是继承,则必须有super继承父类当中的属性
    this.grade = grade;
  }
  speak(){
    console.log('重写了父类继承过来的方法!')
  }
  study(){
    // 思考

推荐阅读