原型、原型链和class、继承

157 阅读1分钟

class

class Student {
//   构造函数 ,传入一些参数
  constructor(name,number){
    this.name = name
    this.number = number
  }
//		定义一些方法
  sayHi(){
    console.log(
      `姓名 ${this.name},number is ${this.number}`
    )
  }
}

// 通过类声明示例
const xiao = new Student('x',100)
console.log(xiao.name)
console.log(xiao.number)
xiao.sayHi()
"x"
100
"姓名 x,number is 100"

继承

  • extends
  • super
  • 扩展或重写方法
// 父类
class People {
  constructor(name) {
    this.name = name
  }
  eat() {
      console.log(`${this.name} eat something`)
  }
}

// 子类
class Student extends People {
  constructor(name,number){
//     将name传给people
    super(name)
    this.number = number
  }
  sayHi () {
    console.log(`name is ${this.name} number is ${this.number}`)
  }
}

// 子类
class Teacher extends People {
  constructor(name,major){
//     将name传给people
    super(name)
    this.major = major
  }
  teach () {
    console.log(`name is ${this.name} number is ${this.major}`)
  }
}
// 通过类声明示例
const xiao = new Student('x',100)
console.log(xiao.name)
console.log(xiao.number)
xiao.sayHi()
xiao.eat()

const wang = new Teacher('xxx','math')
console.log(wang.name)
console.log(wang.major)
wang.teach()
wang.eat()

//"x"
// 100
// "name is x number is 100"
// "x eat something"
// "xxx"
// "math"
// "name is xxx number is math"
// "xxx eat something"

子类通过extends继承people的关系,然后通过super将name传递回去,让两者建立联系

通过extens,子类可以继承父类的方法,然后通过super可以建立两者之间的关系

类型判断 —— instanceof

// 以下都是true
xiao instanceof Student  //xiao先继承student
xiao instanceof People   //student继承people
xiao instanceof Object

[] instanceof Array
[] instanceof Object

{} instanceof Object

原型

// class 实际上是函数,可见是语法糖
typeof People
typeof Student

// 隐式原型和显示原型
console.log(xiao.__proto__)
console.log(Student.prototype)
console.log(xiao.__proto__ === Student.prototype)

关系

  • 每个class都有显示原型prototype
  • 每个实例都有隐式原型__proto__
  • 实例的__proto__指向对应的classprototype

基于原型的执行规则

  • 获取属性xiao.name或者执行方法xiao.sayhi()
  • 先在自身属性和方法中寻找
  • 如果找不到则自动去__proto__中查找

原型链

console.log(Student.prototype.__proto__) //显示原型中隐式原型
console.log(People.prototype)
console.log(People.prototype === Student.prototype.__proto__)

再看instanceof

顺着隐式原型进行查找

  • class是ES6语法规划,由ECMA委员会发布
  • ECMA只规定语法规则,即我们代码的书写规范,不规定如何实现

题目

\

\