ES6的class中的静态属性和方法 static关键字

9,248 阅读2分钟

类(class)

前瞻结论

  • 1 静态方法使用static关键字来声明
  • 2 调用类的静态方法,需要使用 类本身调用
  • 3 在类里面的,静态方法中调用其他静态方法,需要使用this关键字
  • 4 在非静态方法中,不能使用this关键字来访问静态方法
    • 1 通过类名来调用
    • 2 通过 this.constructor来调用

通过 static 关键字定义静态方法。不能在类的实例上调用静态方法,而应该通过类本身调用。这些通常是实用程序方法,例如创建或克隆对象的功能。

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."

语法:

static methodNAme() {...}

描述

静态方法调用直接在类上进行,不能在类的实例上调用。静态方法通常用于创建实用程序函数。

调用静态方法

静态方法调用同一个类中的其他静态方法,可使用 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 关键字来访问静态方法。而是要用类名来调用:CLASSNAME.STATIC_METHOD_NAME() ,或者用构造函数的属性来调用该方法: this.constructor.STATIC_METHOD_NAME().

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.';
    }
}

总结

1 静态方法使用static关键字来声明 2 调用类的静态方法,需要使用 类本身调用 3 在类里面的,静态方法中调用其他静态方法,需要使用this关键字 4 在非静态方法中,不能使用this关键字来访问静态方法

  • 1 通过类名来调用
  • 2 通过 this.constructor来调用