一、查阅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:
- 对标签属性(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:'霍格沃兹'
}