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 有三种作用, 第一是作为构造函数直接调用,第二种是作为父类实例, 第三种是在子类中的静态方法中调用父类的静态方法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这是16年5月份编辑的一份比较杂乱适合自己观看的学习记录文档,今天18年5月份再次想写文章,发现简书还为我保存起的...
    Jenaral阅读 2,841评论 2 9
  • 整理来自互联网 1,JDK:Java Development Kit,java的开发和运行环境,java的开发工具...
    Ncompass阅读 1,553评论 0 6
  • class的基本用法 概述 JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子: ...
    呼呼哥阅读 4,127评论 3 11
  • 一:java概述: 1,JDK:Java Development Kit,java的开发和运行环境,java的开发...
    慕容小伟阅读 1,836评论 0 10
  • 爸,去年我想去市团委,在我的前途问题上,我总愿意跟你讲,你离职这么多年,可我总觉得你可以帮我找到人。我现在清晰的记...
    李弯弯阅读 166评论 0 0