本文介绍了ECMAScript 6 是否有抽象类的约定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶在阅读 ES6 时我找不到任何关于抽象类的信息.(我所说的抽象类"指的是 Java 的含义,其中抽象类声明子类必须实现的方法签名才能实例化).

I was surprised that I couldn't find anything about abstract classes when reading up on ES6. (By "abstract class" I'm talking about the Java meaning of it, in which an abstract class declares method signatures that a subclass must implement in order to be instantiable).

有谁知道在 ES6 中实现抽象类的任何约定?能够通过静态分析捕获抽象类违规会很好.

Does anyone know of any conventions that have taken hold to implement abstract classes in ES6? It would be nice to be able to catch an abstract class violation with static analysis.

如果我在运行时引发错误以表示尝试抽象类实例化,错误会是什么?

If I were to raise an error at runtime to signal an attempt at abstract class instantiation, what would the error be?

推荐答案

ES2015 没有 Java 风格的类,这些类为您想要的设计模式提供了内置的启示.但是,它有一些可能有用的选项,具体取决于您要完成的任务.

ES2015 does not have Java-style classes with built-in affordances for your desired design pattern. However, it has some options which may be helpful, depending on exactly what you are trying to accomplish.

如果你想要一个不能被构造但其子类可以构造的类,那么你可以使用new.target:

If you would like a class that cannot be constructed, but whose subclasses can, then you can use new.target:

class Abstract {
  constructor() {
    if (new.target === Abstract) {
      throw new TypeError("Cannot construct Abstract instances directly");
    }
  }
}

class Derived extends Abstract {
  constructor() {
    super();
    // more Derived-specific stuff here, maybe
  }
}

const a = new Abstract(); // new.target is Abstract, so it throws
const b = new Derived(); // new.target is Derived, so no error

有关new 的更多详细信息.target,您可能想阅读 ES2015 中的类如何工作的一般概述:http://www.2ality.com/2015/02/es6-classes-final.html

如果您特别需要实现某些方法,您也可以在超类构造函数中检查:

If you're specifically looking for requiring certain methods be implemented, you can check that in the superclass constructor as well:

class Abstract {
  constructor() {
    if (this.method === undefined) {
      // or maybe test typeof this.method === "function"
      throw new TypeError("Must override method");
    }
  }
}

class Derived1 extends Abstract {}

class Derived2 extends Abstract {
  method() {}
}

const a = new Abstract(); // this.method is undefined; error
const b = new Derived1(); // this.method is undefined; error
const c = new Derived2(); // this.method is Derived2.prototype.method; no error

这篇关于ECMAScript 6 是否有抽象类的约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 10:02