js中的static

一、查阅MDN文档:

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

  • 静态方法调用同一个类中的其他静态方法,可使用 this 关键字。
class StaticMethodCall {
    static staticMethod() {
        return 'Static method has been called';
    }
    static anotherStaticMethod() {
        return this.staticMethod() + ' 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.';
    }
}

二、目前遇到的一些static:

  1. 对标签属性(props)进行类型、必要性的限制 写在类本身上:
    static propTypes = {
        name:PropTypes.string.isRequired,   //限制name必传且为字符串
        age:PropTypes.number,   //限制name必传且为字符串
        college:PropTypes.string.isRequired,   //限制college为字符串
        school:PropTypes.string,   //school
        curse:PropTypes.func    //限定curse为函数
    }
    //设置默认值
    static defaultProps = {
        age:14,
        school:'霍格沃兹'
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值