详解 JavaScript “类”

83 阅读1分钟

前言

大家好,我是itchao,最近我又在复习 JavaScript 知识,整理一下 “类” 相关知识点

笔记整理自 coderwhy 老师的 《深入 JavaScript 高级语法》,感谢 coderwhy 老师详细全面的讲解

class 类的基本概念

  • 类是 ES6 新特性
  • 关键字是 class

类的两种形式:

  • 声明式(常用)
class Person {
}
  • 表达式
const Person = class {
}

类的基本使用:

class Person {
}

// 类使用 new 关键字,生成对象
const p1 = new Person()
  • constructor 构造器(接收来自 new 生成对象时的参数)
class Person {
constructor(name, age) {
// 此时的 this 指向 new 生成的对象
 this.name = name
 this.age = age
 }
 
 // 类中书写的方法,可以通过 new 生成的对象直接调用
 getInfo() {
 console.log('名字:', this.name)
 console.log('年龄:', this.age)
 }
}

const p1 = new Person('itchao', 18)

console.log(p1)
// Person { name: 'itchao', age: 18 }

p1.getInfo()
// 名字:itchao
// 年龄:18
  • static 静态方法\类方法(通过类直接调用)
class Person {
static classFn() {
console.log('打印的类方法')
 }
}

Person.classFn()
// 打印的类方法

class 类的特性

原型链关系

  • 对象.__proto__ === 类.prototype
class Person {
}

const p1 = new Person()
console.log(p1.__proto__ === Person.prototype)
// true

继承性

  • 子类继承父类的关键字 extends
  • 子类调用父类的关键字 super
class ParentClass {
  constructor(name, age) {
  this.name = name
  this.age = age
  }
  
  parentPlaying() {
  console.log(this.name + ' parentPlaying')
  }
}

class ChildClass {
  constructor(name, age, height) {
   // 复用父类属性
  super(name, age)
  this.height = height
  }
  
  childPlaying() {
  // 利用 super 使子类直接调用父类的方法
  super.parentplaying()
  console.log(this.name + ' childPlaying')
  }
}

const c1 = new ChildClass('itchao', 18, 1.88)
console.log(c1)
// ChildClass { name: 'itchao', age: 18, height: 1.88 }

c1.childPlaying()
// itchao parentPlaying
// itchao childPlaying

结语

  • 谢谢大家阅读,如果有更好的见解,欢迎提出,提前道谢
  • 以后我对 “类” 知识有更深入的理解也会继续完善该笔记