我已经建立了一个错误类层次结构,从一个纯粹用于子类化的BaseError类开始。我已经使用Object.create(Error.prototype)设置了原型,并使用当前子类的名称重写了堆栈。名称是在称为configure的方法中设置的,该方法需要由子类实现。

问题是,尽管我将configure方法显式添加到BaseError的原型中,但实际上在原型链中不可访问。

javascript - 子类化错误:添加原型(prototype)方法无效-LMLPHP

我认为这与__proto__实例属性与prototype属性有关。

javascript - 子类化错误:添加原型(prototype)方法无效-LMLPHP

这是代码(从Typescript定义转换而来)

var BaseError = (function () {
    function BaseError(msg) {
        var err = Error.apply(null, arguments);
        this.message = err.message;

        this.configure();

        if (err.stack) {
            this.stack = rewriteStack(err.stack, this.name);
        }

        if (typeof this.name === 'undefined')
            throw new NotImplementedError('must set "name" property in the configure call');
    }

    return BaseError;
})();

Framework.BaseError = BaseError;

// weird stuff need to happen to make BaseError pass an "instanceof Error"
BaseError.prototype = Object.create(Error.prototype);

BaseError.prototype.configure = function () {
    throw new NotImplementedError(+' This method must be implemented in the overriding class!');
};

最佳答案

您正在执行Object.create(BaseError),而不是应该执行的Object.create(BaseError.prototype)

07-24 17:43