通过经典的继承通过函数构造器在NodeJS的CustomError类中未设置message字段值

时间:2018-12-09 14:35:07

标签: javascript node.js error-handling prototypal-inheritance javascript-inheritance

这种情况很好:

class CustomError2015 extends Error {
    constructor(message) {
        super(message); // here the message is set correctly
        console.log("Message: " + this.message); 
    }
}

throw new CustomError2015("ECMAScript 2015 class inheritance");

我希望这将以相同的方式工作,但事实并非如此:

function CustomError(message){
    Error.call(this, message); // here the message IS NOT set
    console.log("Message: " + this.message); 
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;

throw new CustomError("CustomError function-like inheritance");

我想知道为什么吗? 我的代码有什么问题吗?

* These code samples' playground.

1 个答案:

答案 0 :(得分:0)

ErrorArray)中的类型是 exotic ,这表示它们的构造函数不正常,并且其实例的对象也不正常,它们是特殊的内部对象。因此:

  Error.call(this, message)

无效,因为Error必须返回一个奇异的对象,而this是常规对象,并且引擎无法将其转换为另一个。因此,它将返回一个新的外来错误(您在代码中将其忽略):

  let exotic = Error.call(this);
  exotic === this // false

该消息设置在该奇异对象上,而不是this上。

这在类中起作用,因为在访问super(....)之前会调用this,因此this可以是奇异对象,没有类就无法复制该行为。

read on