139 阅读1分钟

ES6中的类

类的写法

```
class Person{
    height="178cm";
    constructor(name,age){
        //属性
        this.name = name;
        this.age = age;
    }
    //方法
    getName(){
        console.log("姓名是:"+this.name);
    }
}
let student = new Person("张三",20);
student.getName();
​
```

静态方法和属性:实例不会继承的属性和方法

```
class Person{
    //静态方法
    static hobby(){
        console.log("喜欢篮球");
    }
}
//静态属性
Person.height = "178cm";
//通过类来调用
Person.hobby();
console.log(Person.height);
```

私有成员 “#”符号

```
class Person{
    #height = "178cm";
    constructor(name){
        this.name = name;
    }
}
```

访问器属性

get set

```
class Person{
    constructor(name){
        this.name =name
    }
    get name(){
        console.log('get');
    }
    set name(newValue){
        console.log('set', newValue);
    }
}
let zs = new Person('张三')
zs.name //get
zs.name = '李四' // 'set 李四
```

类的继承

class Dad{
    name = "张三";
    age = 40;
    constructor(height){
        this.height = height;
    }
    hobby(){
        console.log("喜欢篮球");
    }
}
class Son extends Dad{
    constructor(height){
        //表示父类的构造函数
        super(height);
        // 子类的属性要放在super后面
        this.age = 18
    }
}

super特点

  • super只能在子类中使用,可以在constructor 及 函数或静态方法中使用
  • 不能单独使用super
  • super调用类似函数调用可以根据父类构造函数传参数
  • 如果子类中没有constructor,子类会自动调取super()且传入参数到父类
  • 子类中需要在调取super之后调用this

抽象基类 :自定义的 不允许直接被实例化,存储的是类的共有特征 可以被继承

```
    class AbstractPerson{
        constructor(){
            if(new.target===AbstractPerson){
               throw new Error("AbstractPerson 类不能被实例化");
            }
        }
    }
    class Person extends AbstractPerson{
​
    }
    let zhangsan = new Person();
```

如何实现链式调用?

  1. return this
  2. return 实例化对象
// 链式调用
 class Person{
     fn(){
         console.log('fn');
         // return this
         return new Person()
     }
 }
 let zs = new Person()
 zs.fn().fn()