FrankKai / FrankKai.github.io

FE blog
https://frankkai.github.io/
363 stars 39 forks source link

es6 class 之 static #201

Open FrankKai opened 4 years ago

FrankKai commented 4 years ago

class在面向对象设计中非常有用,static关键字值得好好学习一下。

static关键字速览

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调用

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方法的。可以使用以下两种方式:

static使用综合示例

这里重点关注子class中,是如何调用父class中的static的:extends和super

下面的例子从3个方面解释了static的使用。

  1. static方法在class中如何实现
  2. 拥有static成员的class可以被子class继承
  3. 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