了解JavaScript错误对象

Understanding the JavaScript Error object

本文关键字:对象 错误 JavaScript 了解      更新时间:2023-09-26

我不确定像message这样的属性在Error JavaScript对象上下文中是如何工作的,所以我做了一个测试:

var e = new Error('foo');
console.log(Object.keys(e)); // displays "[]"

现在:

var e = new Error();
e.message = 'foo';
console.log(Object.keys(e)); // displays "['message']"

我想,当一条消息被传递给构造函数时,这个字段将属于Error对象原型,但我不知道如果我能用我的一个类来重现同样的行为,以更好地理解:

function C(msg) {
  // **What to write here to make msg belong to the C prototype?**
}
var c = new C('foo');
console.log(Object.keys(c)); // **I would like it to display []**

我的问题是:如何在C类中模拟Error消息属性行为?

您可以使用Object.defineProperty()定义一个不可枚举的属性:

function C(msg) {
    // you an use  enumerable: false  in the third argument, 
    // but it is false by default
    Object.defineProperty(this, "message", { value: msg });
}
var c = new C("hello");
console.log(Object.keys(c).length); // 0
console.log(c.message);             // hello

如果你不关心message是否可枚举(从你的问题中还不清楚),那么你可以使用这个普通的方法:

function C(msg) {
    this.message = msg;
}
var c = new C("hello");
console.log(Object.keys(c).length); // 1
console.log(c.message);             // hello