如何在JavaScript中创建无法实例化的抽象基类

时间:2015-05-31 15:34:51

标签: javascript inheritance design-patterns

我有一个班级

function Node() {
    //implementation
}

和另一个班级

function AttributionalNode() {
    this.prototype.setAttr = function (attr) {
        this.atText = attr;
    };
}

AttributionalNode.prototype = new Node();
AttributionalNode.prototype.constructor = AttributionalNode;

如何使类Node()无法实例化? 例如,当我尝试

var node = new Node();

所以它抛出一个例外?

5 个答案:

答案 0 :(得分:44)

在支持ECMAScript 2015(又名ES6)类语法的JavaScript引擎中,这可以使用new.target元属性来完成:

function Node() {
   if (new.target === Node) throw TypeError("new of abstract class Node");
}

或使用类语法:

class Node {
   constructor () {
      if (new.target === Node) throw TypeError("new of abstract class Node");
   }
}

在任何一种情况下,只需将AttributionalNode定义为:

class AttributionalNode extends Node {
   constructor () {
      super();
   }
   setAttr(attr) {
      this.atText = attr;
   }
}

new Node();               // will throw TypeError
new AttributionalNode();  // works fine

有关new.target的更详细说明,请参阅this document的第4.2节。

答案 1 :(得分:12)

这样可行:



function Node() {
    if (this.constructor === Node) {
        throw new Error("Cannot instantiate this class");
    }
}

function AttributionalNode() {
    Node.call(this); // call super
}

AttributionalNode.prototype = Object.create(Node.prototype);
AttributionalNode.prototype.setAttr = function (attr) {
    this.atText = attr;
};
AttributionalNode.prototype.constructor = AttributionalNode;

var attrNode = new AttributionalNode();
console.log(attrNode);
new Node();




注意:你不能在构造函数中引用this.prototype,因为原型只是构造函数的属性,而不是实例的属性。

另外,see here是关于如何正确扩展JS类的好文章。

答案 2 :(得分:6)

根据@ levi的回答,您可以使用与ES6一起使用的类似解决方案(因为new.target尚未建立):

你可以看到它在Babel的repl:http://bit.ly/1cxYGOP

上运行
class Node {
    constructor () {
      if (this.constructor === Node) 
          throw new Error("Cannot instantiate Base Class");
    }

    callMeBaby () {
      console.log("Hello Baby!");
    }
}

class AttributionalNode extends Node {
  constructor () {
    super();
    console.log("AttributionalNode instantiated!");
  }
}

let attrNode = new AttributionalNode();
attrNode.callMeBaby();

let node = new Node();

答案 3 :(得分:0)

基于这些评论,我写了

class AbstractClass {
    constructor() {
        if(new.target === AbstractClass || this.__proto__.__proto__.constructor === AbstractClass)
            throw new TypeError("Cannot construct "+ this.constructor.name + " class instances directly");
        let exceptions = {};
        let currProto = this;
        while(currProto.constructor !== AbstractClass ) {
            for(let method of (currProto.constructor.abstractMethods || [])) {
                if("function" !== typeof(this[method]))
                    exceptions[method] = currProto.constructor.name;
            }
            currProto = currProto.__proto__;
        }
        if(0 !== Object.keys(exceptions).length) {
            let exceptionsArray = [];
            for(let method in exceptions) {
                exceptionsArray.push( exceptions[method] + "." + method);
            }
            exceptionsArray.sort();
            throw new TypeError("Must override the following methods: " + exceptionsArray.join(", "));
        }
    }
    }

用法:

class MyAbstractClass1 extends AbstractClass {
    static abstractMethods = [
        "myMethod1", // (x:string, y:string): string
        "myMethod2" // (y:string, z:string): string 
    ]
}

class MyAbstractClass2 extends MyAbstractClass1 {
    static abstractMethods = [
        "myMethod3", // (x:string, y:string): string
        "myMethod4" // (y:string, z:string): string 
    ]
}

class MyClass extends MyAbstractClass2 {
    myMethod1(x, y){return "apple"}
}

new MyClass()
//Error

答案 4 :(得分:0)

尽管问题有一个 javascript 标记,但是由于当今许多项目都在JS之上使用 typescript ,所以值得注意的是TS具有support for abstract classes and methods开箱即用

abstract class Animal {
    abstract makeSound(): void;
    move(): void {
        console.log("roaming the earth...");
    }
}