Class

class 并不是ES6的新的语法 而只是原有语法的语法糖,是一种特殊的函数(class的类型就是函数)

class类只能使用new关键字来调用和初始化

//ES6前
function User(name, email) {
    this.name = name
    this.email = email
    return this
}
User.prototype.info = function() {
    console.log(`hi, i am ${this.name}`)
}
const lyy = new User("lyy", "sina.com")

新的class写法

class User {
    constructor(name, email) {
        this.name = name
        this.email = email
    }
    info() {
        console.log(`hi, i am ${this.name}`)
    }
}

特性

静态方法

class User {
    constructor(name, email) {
        this.name = name
        this.email = email
    }
    info() {
        console.log(`hi, i am ${this.name}`)
    }
    static description() {
        console.log("I am user")
    }
}
User.description() //I am user

Set和Get方法

class User {
    constructor(name, email) {
        this.name = name
        this.email = email
    }
    set github(value) {
        this.githubName = value
    }

    get github() {
        return this.githubName
    }
}

计算属性

类似对象章节的写法 使用[ ]来写计算属性

let methodName = "info"
class User {
    constructor(name, email) {
        this.name = name
        this.email = email
    }
    //计算属性 此时方法名为 info() {}
    [methodName]() {
        console.log(`hi, i am ${this.name}`)
    }
}

类的继承

ES6中通过extends关键字来实现继承

class Animal {
    constructor(name) {
        this.name = name
        this.belly = []
    }

    eatFood(food) {
        this.belly.push(food)
    }

}

//extends 关键字实现继承
class Dog extends Animal {
    constructor(name, age) {
        //使用super关键字来继承父类的属性和方法
        super(name)
        this.age = age
    }

    bark() {
        console.log("wang wang wang")
    }
}

const huanhuan = new Dog("wtt", 23)

扩展内建对象

我们通过es6的类可以扩展 内建对象在原有功能的基础上实现自己需要的功能

补充

ES5中的类和静态方法

function Person(name,age) {
//构造函数里面的方法和属性
      this.name=name;
      this.age=age;
      this.run=function(){
           console.log(`${this.name}---${this.age}`)
       }
}
//原型链上面的属性和方法可以被多个实例共享
Person.prototype.sex='男';
Person.prototype.work=function(){
      console.log(`${this.name}---${this.age}---${this.sex}`);
 }
//静态方法
Person.setName=function(){
      console.log('静态方法');
}
var p=new Person('zhangsan','20');   /*实例方法是通过实例化来调用的,静态是通过类名直接调用*/
p.run();
p.work();

Person.setName();  /*执行静态方法*/