概述
-
在ES6中,class (类)作为对象的模板被引入,可以通过 class 关键字定义类。
-
class 的本质是 function。
-
它可以看作一个语法糖,让对象原型的写法更加清晰、更像面向对象编程的语法。
-
类不可重复声明
-
类定义不会被提升,这意味着必须在访问前对类进行定义,否则就会报错
类定义
// 匿名类
let Example = class {
constructor(a) {
this.a = a;
}
}
// 命名类
let Example = class Example {
constructor(a) {
this.a = a;
}
}
//类声明
class Example {
constructor(a) {
this.a = a;
}
}
类的属性
属性:ES6的类中可以直接定义变量,变量也可以被定义在constructor中。也可以是静态属性
class People {
b = 10;
constructor() {
this.a = 100; //定义变量
this.c=20;
}
static d=1;//静态属性
}
let p = new People();
console.log(p.a,p);//100 People {b: 10, a: 100, c: 20, d: 1}
//可以创建函数时,传递参数
class People1 {
constructor(a,b) {
this.x = a;
this.y = b;
}
}
let p1 = new People1(1,2);
类的方法
constructor 方法是类的默认方法,创建类的对象时被调用。也被称为类的构造方法(构造函数、构造器)。一个类中有且仅有一个构造方法。不写构造函数 系统会默认有一个空的构造运行
原型方法:不需要使用function关键字,通过“对象.原型方法”调用
class Person{
//对象的原型对象的方法
say(){
console.log(111)
}
}
静态方法:使用static修饰,调用时不需要创建对象,直接通过“类名.静态方法”调用
class People {
static say2(){
console.log(222)
}
}
类的继承
-
解决代码的复用
-
使用extends关键字实现继承
-
子类可以继承父类中所有的方法和属性
-
子类只能继承一个父类(单继承),一个父类可以有多个子类
-
子类的构造方法中必须有super()来指定调用父类的构造方法,并且位于子类构造方法中的第一行
-
子类中如果有与父类相同的方法和属性,将会优先使用子类的(覆盖)
class Person { hair='black' constructor(name) { this.name = name this.eat = function () { console.log(this.name + "吃饭") } } run() { console.log(this.name + "跑步") } } var p1 = new Person("karen") var p2 = new Person("jack") console.log(p1, p2) //Person {hair: 'black', name: 'karen', eat: ƒ} //Person {hair: 'black', name: 'jack', eat: ƒ} //run函数也被继承 //继承用extends关键字 class Student extends Person { constructor(name) { super(name) //让Person类的构造函数的逻辑去帮我们构建对象空间 this.age = 20 this.book = "书名" } hair='yellow' } var s1 = new Student("marry") console.log(s1) //Student {hair: 'yellow', name: 'marry', age: 20, book: '书名', eat: ƒ}
文章主要摘自