Class是一个特殊的函数,用来生产对象,实现继承。

静态方法:

直接通过类来调用,这就称为“静态方法”

  1. class Foo {
  2. static classMethod() {
  3. return 'hello';
  4. }
  5. }
  6. Foo.classMethod() // 'hello'
  7. var foo = new Foo();
  8. foo.classMethod()

静态属性:

静态属性指的是 Class 本身的属性

  1. // 老写法
  2. class Foo {
  3. // ...
  4. }
  5. Foo.prop = 1;
  6. // 新写法
  7. class Foo {
  8. static prop = 1;
  9. }

实例属性:

  1. class IncreasingCounter {
  2. constructor() {
  3. this._count = 0;
  4. }
  5. get value() {
  6. console.log('Getting the current value!');
  7. return this._count;
  8. }
  9. increment() {
  10. this._count++;
  11. }
  12. }

也可以:

  1. class IncreasingCounter {
  2. _count = 0;
  3. get value() {
  4. console.log('Getting the current value!');
  5. return this._count;
  6. }
  7. increment() {
  8. this._count++;
  9. }
  10. }