Static关键字

  • The static keyword defines a static method for a class.
  • Static修饰的方法只能通过类名来调用,不能使用具体对象来调用,常用来做公用方法utitly
  • 同一个class下的不同静态方法可以通过this来互相调用, 非静态方法不能直接通过this来调用静态方法

  >class Person {

    static sayHello()

    {

      console.log('hello') ;

      this.sayWorld();

    }

    static sayWorld()

    {

      console.log('world')

    }

  }

  • 非静态方法可以通过类名来调用静态方法,或者通过this.constructor.staticMethod()来调用静态方法

  > class Person {

    constructor(){

      this.constructor.foo() ;

      Person.foo();

    }

    static foo()

    {

      console.log('helloworld')

    }

  }

  • 存在继承关系的两个类之间,方法的调用,通过super来显示的调父类里面的静态方法

  > class Parent {

    static sayHello()

    {

      console.log('parent say hello')

    }

  }

  > class Child extends Parent{

    static sayHello()

    {

      console.log('child say hello');

      super.sayHello() ;

    }

    static sayWorld()

    {

      console.log('child say world') ;

    }

    test()

    {

      console.log('child say test') ;

    }

  }

  Parent.sayHello() // parent say hello

  Child.sayHello() // child say hello , parent say hello

  Child.sayWorld() // child say world

  Child.test() // not a function

  new Child().sayHello() // not a function

  new Child().sayWorld() // not a function

原文地址:https://www.cnblogs.com/chihaiping/p/6371271.html