es6类

ES6类

定义:

1
2
3
4
5
6
7
8
9
10
class Animal {
    //构造函数,创建这个类时会执行的函数
    constructor(color){
        //this当前对象
        console.log("构造")
        this.color=color
    }
}
const myCat = new Animal("白");
console.log(myCat)

  

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

类的继承   class Cat extends Animal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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关键字可以声明静态的方法,静态方法归属于类而不是实例 也可声明静态变量
普通的方法归属于实例,需要通过实例调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    class Animal {<br>    //静态变量
        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/chengxiao35/p/13610808.html