ES6中类的静态方法=> static 的使用

栏目: JavaScript · 发布时间: 7年前

内容简介:类就是实例的原型,以前我们一般会new一个test(),有在类中(test)定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”

类就是实例的原型,以前我们一般会new一个test(),有在类中(test)定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”

class Father {
    static testMethod() {
        return 'hello';
    }
}

Father.testMethod() // 'hello'
var Child = new Father();
Child.testMethod()
// TypeError: Child.testMethod is not a function

这是因为Father中的testMethod方法是静态方法(有static关键字),不会被实例化出来的Child继承,
当前testMethod方发可以直接在Father类上调用,如果在实例化出来的类上调用会抛出一个错误,表示不存在该方法。
复制代码

父类的静态方法,可以被子类继承。

class Father {
  static testMethod() {
    return 'hello';
  }
}
class Child extends Father {

}
Child.classMethod(); // 'hello'

上面代码中,父类Father有一个静态方法,子类Child可以调用这个方法,因为这是通过extends继承的,不是通过new()实例化得到的
复制代码

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Data Structures and Algorithms in Java

Data Structures and Algorithms in Java

Robert Lafore / Sams / 2002-11-06 / USD 64.99

Data Structures and Algorithms in Java, Second Edition is designed to be easy to read and understand although the topic itself is complicated. Algorithms are the procedures that software programs use......一起来看看 《Data Structures and Algorithms in Java》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具