如何在无法实例化的JavaScript中创建抽象基类 [英] How to create Abstract base class in JavaScript that can't be Instantiated

查看:84
本文介绍了如何在无法实例化的JavaScript中创建抽象基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类

function Node() {
    //implementation
}

另一个类

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

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

如何使类Node()不能被实例化?
例如,当我尝试

How to make class Node() so it can't be instantiated? e.g when I try

var node = new Node();

所以它会抛出异常?

推荐答案

这将工作:

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 ,因为原型只是构造函数的属性,而不是实例。

Note: you cannot refer to this.prototype inside the constructor, as the prototype is only a property of the constructor function, not of the instances.

此外,看到这里有一篇关于如何正确扩展JS类的好文章。

Also, see here for a good article on how to properly extend JS classes.

这篇关于如何在无法实例化的JavaScript中创建抽象基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆