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

查看:24
本文介绍了如何在 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天全站免登陆