ES6类

ES6类

定义:

    class Animal {
        //构造函数,创建这个类时会执行的函数
        constructor(color){
            //this当前对象
            console.log("构造")
            this.color=color
        }
    }
    const myCat = new Animal("白");
    console.log(myCat)

  

  • constructor: 构造函数
  • this : 当前实例
  • super: 它的父类

类的继承   class Cat extends Animal

    class Animal {
        constructor(color){
            this.color= color;
        }
        eat() {
            console.log("吃饭");
        }
    }
    //继承
    class Cat extends Animal {
        // 构造函数
        constructor(color,name){
            //父类
            super(color);
            // 当前实例
            this.name = name;
        }
        eat(){
            super.eat();
            console.log("吃啊了")
        }
    }

    let myCat = new Cat("黑白","皮皮")
    myCat.eat();
    console.log(myCat.name);
    console.log(myCat.color)

  

通过static关键字可以声明静态的方法,静态方法归属于类而不是实例 也可声明静态变量
普通的方法归属于实例,需要通过实例调用
    class Animal {
    //静态变量 static name = "动物的类" constructor(color,name){ this.color = color; this.name = name; } //通过static关键字可以声明静态的方法,静态方法归属于类而不是实例 static getname() { console.log("静态方法"); return this; } //普通方法归属于实例 eat(){ console.log(this.name +"吃饭"); } } let myCat =new Animal("白色","学学"); let yourCat = new Animal("白色", "球球"); //通过实例调用方法 myCat.eat(); yourCat.eat(); //实例没有静态方法 // console.log(myCat.getname()); console.log(Animal.getname()); console.log(Animal.name); // console.log(Animal.prototype.name);

  

原文地址:https://www.cnblogs.com/wenaq/p/13610622.html