Open
Description
class在面向对象设计中非常有用,static关键字值得好好学习一下。
- static关键字速览
- static方法调用示例
- static使用综合示例
static关键字速览
- static关键字为class定义了一个静态的方法。
- static method不能被class的实例调用,只能被class自身调用。
- static method通常是utility函数,比如创建或者克隆对象的函数。
class ClassWithStaticMethod {
static staticMethod() {
return 'static method has been called.';
}
}
console.log(ClassWithStaticMethod.staticMethod()); // 'static method has been called.'
语法
static methodName() { ... }
描述
static方法的调用只能通过class直接调用。
static方法不能被class的实例调用。
static方法通常用于创建utility函数。
static方法调用示例
class内部,static方法的调用分两种情况:static方法内部用this调用;非-static方法内部用CLASSNAME.xxx
调用或者this.constructor.xxx
调用。
- class中的另一个static调用:
this.staticMethod()
- class中的constructor和method调用
StaticMethodCall.staticMethod()
this.constructor.staticMethod()
class中的另一个static调用
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'
class中的constructor和method调用
在非static方法内部,比如说constructor和prototype method内部,是无法通过this获取到static方法的。可以使用以下两种方式:
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.';
}
normalMethod() {
console.log(StaticMethodCall.staticMethod());
// 'static method has been called.'
console.log(this.constructor.staticMethod());
// 'static method has been called.'
}
}
static使用综合示例
这里重点关注子class中,是如何调用父class中的static的:extends和super
。
下面的例子从3个方面解释了static的使用。
- static方法在class中如何实现
- 拥有static成员的class可以被子class继承
- static方法何时可以调用何时不可以调用
class Triple {
static triple(n = 1) {
return n * 3;
}
}
class BiggerTriple extends Triple {
static triple(n) {
return super.triple(n) * super.triple(n);
}
}
console.log(Triple.triple()); // 3
console.log(Triple.triple(6)); // 18
var tp = new Triple();
console.log(BiggerTriple.triple(3));
// 81 不会被父class实例化影响
console.log(tp.triple());
// 'tp.triple is not a function'.
参考资料:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static