ES6 class的static关键字

148 阅读1分钟

声明

  • 属于类而不是类的实例的方法

    • 在类加载时就已经存在,可以通过类名直接调用,而无需实例化类
  • 用于创建实用程序函数

class ClassWithStaticMethod {

  static staticProperty = 'someValue';
  static staticMethod() {
    return 'static method has been called.';
  }

}

console.log(ClassWithStaticMethod.staticProperty);
// output: "someValue"
console.log(ClassWithStaticMethod.staticMethod());
// output: "static method has been called."

调用

静态方法中调用其他静态方法需要使用this关键字

class StaticMethodCall {
    static staticMethod() {
        return 'Static method has been called';
    }
    static anotherStaticMethod() {
        return this.staticMethod() + ' from another static method';
    }
}
console.log(StaticMethodCall.staticMethod())
// 'Static method has been called'

console.log(StaticMethodCall.anotherStaticMethod())
// 'Static method has been called from another static method'

在非静态方法中,通过类名和this.constructor来调用

用类名来调用:CLASSNAME.STATIC_METHOD_NAME() 

用构造函数的属性来调用该方法: this.constructor.STATIC_METHOD_NAME()

  • 不能使用this关键字来访问静态方法
class StaticMethodCall {
    constructor() {
        console.log(StaticMethodCall.staticMethod());
        // 'static method has been called.'
        console.log(this.constructor.staticMethod());
        // 'static method has been called.'
    }
    static staticMethod() {
        return 'static method has been called.';
    }
}

链接:juejin.cn/post/701281…