ES6 新特性:Class

定义一个 class

每一个使用 class 方式定义的类默认都有一个构造函数 constructor() 函数, 这个函数是构造函数的主函数, 该函数体内部的 this 指向生成的实例。

class Person {
    constructor(name) {
        this.name = name;
    }
    say () {
        console.log("hello " + this.name);
    }
};

tom = new Person('tom')
tom.say()

// 运行结果
hello tom

注意: ES6 中声明的类不存在函数声明提前的问题, 类必须先声明再使用,否则会出现异常。




静态方法与静态属性

在类的内部,定义函数的时候, 在函数名前声明了 static, 那么这个函数就为静态函数, 就为静态方法, 不需要实例就可调用:

class Person {
    constructor(name) {
        this.name = name;
    }
    static say () {
        console.log("hello world!");
    }
};

Person.say()

// 运行结果
hello world

只能在类定义完毕以后再定义静态属性:

class Person {
    constructor(name) {
        this.name = name;
    }
    say () {
        console.log("hello " + this.name);
    }
};

Person.hands = 2;
console.log(Person.hands);

// 运行结果
2

不能直接定义属性我们可以使用 setget

class Person {
    constructor(_name) {
        this._name = _name;
    }

    get name() {
        return this._name;
    }
    
    set name(_name) {
        this._name = _name;
    }

    say () {
        console.log("hello " + this.name);
    }
};

// 测试
var tom = new Person('tom')
tom.name // tom

tom.name = 'tommy'
tom.name // tommy




类的继承 extends

本例中 X_Man 继承了 Person 类,使用 extends 关键字表示:

class Person {
    constructor(name) {
        this.name = name;
    }
    say () {
        console.log("hello " + this.name);
    }
};

class X_Man extends Person {
    constructor (name, power) {
        super(name);
        this.power = power;
    }
    show () {
        console.log(this.name + ' has '+ this.power + ' power');
    }
}

logan = new X_Man('logan', 100)
logan.show()

//  运行结果
logan has 100 power

要使用继承的话, 在子类中必须执行 super() 调用父类, 否者编译器会抛错。

在子类中的 super 有三种作用, 第一是作为构造函数直接调用,第二种是作为父类实例, 第三种是在子类中的静态方法中调用父类的静态方法。

猜你喜欢

转载自blog.csdn.net/weixin_34368949/article/details/87154580