class中的static

参考资料

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

class ClassWithStaticMethod {
  static staticMethod() {
    return 'static method has been called.';
  }
}

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

let a = new ClassWithStaticMethod();

a.staticMethod() // 报错

在一个静态方法中调用同一个类中的其他静态方法,可以使用this关键字。

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

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

静态方法不能被实例继承,但可以被子类继承


class Foo {
  static classMethod() {
    return 'hello';
  }
}
Foo.classMethod() // 'hello'

// static方法不能被实例继承
var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function

// static方法可以被子类继承
class Bar extends Foo {
}
Bar.classMethod(); // 'hello'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值