类的静态方法、私有方法

259 阅读1分钟

学习链接: wangdoc.com/es6/class.h…

静态方法

类相当于实例的原型,所有在类中定义的方法,都会被实例继承。

如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。

class Foo {
  static classMethod() {
    return 'hello';
  }
}

Foo.classMethod() // 'hello'  直接通过类来调用

var foo = new Foo();
foo.classMethod() //实例未继承该方法,调用报错
// TypeError: foo.classMethod is not a function

注意:

  1. 如果静态方法包含this关键字,这个this指的是类,而不是实例。
  2. 父类的静态方法,可以被子类继承。
class Foo {
  static classMethod() {
    return 'hello';
  }
}

class Bar extends Foo {
}

Bar.classMethod() // 'hello'
  1. 静态方法也是可以从super对象上调用的。
class Foo {
  static classMethod() {
    return 'hello';
  }
}

class Bar extends Foo {
  static classMethod() {
    return super.classMethod() + ', too';  //在静态方法中,super指向父类。
  }
}

Bar.classMethod() // "hello, too"

私有方法

私有方法和私有属性,是只能在类的内部访问的方法和属性,外部不能访问。ES6只能通过变通方法模拟实现。