Es6-class类

151 阅读1分钟

一 class的定义

1.认识class

人类:类

具体的人:实例、对象

类可以看做是对象的模板,用一个类可以创建出许多不同的对象

2.Class的基本用法

类名一般首字母大写

class Person{}
  class Person {
    // 实例化时执行构造方法,所以必须有构造方法,但可以不写出来
    constructor(name, age) {
      console.log("123132");
      this.name = name;
      this.age = age;
    //一般在构造方法中定义属性,方法不再构造方法中定义
    //   this.speak=()=>{} //false
    }
    speak(){
        console.log('speak');
    } //true
  }

3.class的两种定义方式

声明形式

class Person{
    constructor(){}
}

表达式形式

function Person(){}
const Person=function(){}
const Person=class{
    constructor(){
        console.log("constructor");
    }
    speak(){}
}

new Person

二 属性和方法

1.实例属性

方法就是值为函数的特殊属性

class Person{
    age=18;
    sex='male';
    getSex=function(){
        return this.sex;
    }
    constructor(name,sex){
        this.name=name
        this.sex=sex
    }
    speak(){
        this.age=18;
    }
}

2.静态方法

类的方法

class Person{
    age=18;
    sex='male';
    getSex=function(){
        return this.sex;
    }
    constructor(name,sex){
        this.name=name
        this.sex=sex
    }
    speak(){
       console.log("speak");
    }
    static speak(){
        console.log("人类可以说话");
        // this 指向类
        console.log(this);
    }
}

3.静态属性

类的属性

class Person {
  constructor(name) {
    this.name = name;
  }
  static getVersion(){
      return '1.0'
  }
}

三 继承

extends

1.子类继承父类

class Person{
    constructor(name,sex){
        this.name=name;
        this.sex=sex;
        this.say=function(){
        console.log("say");
        }
    }
    speak(){
        console.log("speak");
    }
    static speak(){
        console.log("说人话");
    }
}
Person.version='1.0';
class Programmer extends Person{
    constructor(name,sex){
        super(name,sex)
    }
}

2.改写继承的属性或方法

class Person{
    constructor(name,sex){
        this.name=name;
        this.sex=sex;
        this.say=function(){
        console.log("say");
        }
    }
    speak(){
        console.log("speak");
    }
    static speak(){
        console.log("说人话");
    }
}
Person.version='1.0';
class Programmer extends Person{
    constructor(name,sex,feature){
        // this.feature=feature //报错
        // this操作不能放在super前面
        super(name,sex,feature)
        this.feature=feature
    }
    //同名覆盖
    speak (){
        console.log("Programmer speak");
    }
    static speak(){
        console.log("Programmer 说人话");
    }
}
Programmer.version='2.0';
const zs= new Programmer("zs",'男','秃头')
console.log(zs.name);
console.log(zs.sex);
console.log(zs.feature);
zs.say()
zs.speak()
Programmer.speak()
console.log(Programmer.version);