类 继承

2021-05-30  本文已影响0人  RickyWu585

构造函数

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(){
  console.log(` hello , ${this.name}, i am ${this.age} years old`)
}
var p = new Person('frank',18)

静态方法

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

相当于

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

继承

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(`my score is ${this.score}`)
  }
}
function Person(name,age){
  this.name = name
  this.age = age
}
Person.prototype.sayHello(){
  console.log('hello world')
}
function Student(name,age,score){
  Person.apply(this,arguments)
  this.score = score
}
function temp(){}
temp.prototype = Person.prototype
Student.prototype = new temp()
Student.prototype.contructor = Student
Student.prototype.sayScore = function(){console.log(`i get ${this.score}`)}

var stu = new Student('frank',18,100) 
上一篇 下一篇

猜你喜欢

热点阅读