您好,欢迎来到知库网。
搜索
您的当前位置:首页类和继承

类和继承

来源:知库网

1.构造函数

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log( `hello, ${this.name}, i am ${this.age} years old`);
  }
}

等价于

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.sayHello = function () {
  console.log(  `hello, ${this.name}, i am ${this.age} years old`);
};

var p = new Person('hunger', 2);

2. 静态方法

class EventCenter {
  static fire() {
    return 'fire';
  }
  static on(){
    return 'on'
  }
}

等同于

function EventCenter(){
}
EventCenter.fire = function(){}
EventCenter.on = function(){}

3.继承

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log( `hello, ${this.name}, i am ${this.age} years old`);
  }
}
class Student extends Person {
  constructor(name, age, score) {
    super(name, age); 
    this.score = score;
  }

  sayScore() {
     console.log(  `hello, ${this.name}, i am ${this.age} years old, i get ${this.score}`);
  }
}

Copyright © 2019- zicool.com 版权所有 湘ICP备2023022495号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务