这种情况很好:
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");
我想知道为什么吗? 我的代码有什么问题吗?
答案 0 :(得分:0)
(Error
,Array
)中的类型是 exotic ,这表示它们的构造函数不正常,并且其实例的对象也不正常,它们是特殊的内部对象。因此:
Error.call(this, message)
无效,因为Error
必须返回一个奇异的对象,而this
是常规对象,并且引擎无法将其转换为另一个。因此,它将返回一个新的外来错误(您在代码中将其忽略):
let exotic = Error.call(this);
exotic === this // false
该消息设置在该奇异对象上,而不是this
上。
这在类中起作用,因为在访问super(....)
之前会调用this
,因此this
可以是奇异对象,没有类就无法复制该行为。