[英]Create my own classList object when the browser does not implement it itself
[英]How does the Error object seems to create properties on itself by his own on Javascript?
好的,我首先想說我知道對此可能有一個非常基本的解釋,所以如果這是一個過於新手的問題,請原諒我。
問題是:為什么在我創建新原型之前 Error.message 屬性不存在?
例子:
let a = new Error('testing')
console.log( a.message ) // 'testing'
但在之前,如果我嘗試訪問 Error 屬性和方法(例如: Object.getOwnPropertyNames(Error)
),則消息屬性甚至都不存在,甚至不存在空字符串,它只是不存在。
之前不應該是空字符串嗎? 創建新原型時,Error 對象如何自行創建新屬性?
getOwnPropertyNames
只返回在對象上設置的屬性,而不是繼承的(原型)屬性。 線索就在名稱中:“自己的”-properties。
舉例:
const a_simple_object_with_no_prototype = {
b: "b",
c: "c"
};
console.log( Object.getOwnPropertyNames( a_simple_object_with_no_prototype ) )
// [ "b", "c" ]
對於具有從原型繼承的屬性的對象,我們會得到不同的結果:
const an_object_used_as_a_prototype = {
a: 789
};
function ConstructorFunction() {
this.b = "b";
}
ConstructorFunction.prototype = an_object_used_as_a_prototype;
const an_object_with_a_prototype = new ConstructorFunction();
an_object_with_a_prototype.c = "c";
console.log( Object.getOwnPropertyNames( an_object_with_a_prototype ) )
// [ "b", "c" ] // does not include "a" which is inherited from the prototype
但在之前,如果我嘗試訪問 Error 屬性和方法(例如:
Object.getOwnPropertyNames(Error)
),則消息屬性甚至都不存在,甚至不存在空字符串,它只是不存在。
那是因為Object.getOwnPropertyNames(Error)
只會列出Error
構造函數的“靜態” 1成員。 如果你執行Object.getOwnPropertyNames( Error.prototype )
那么你會看到它們:
const protoProps = Object.getOwnPropertyNames( Error.prototype );
console.log( protoProps ); // ["constructor", "name", "message", "toString"]
我確實注意到,JavScript 中的Error
對象充滿了一些您無法在 JavaScript 本身中復制的特殊行為,例如其stack
屬性的工作方式,但這超出了您的問題范圍。
1 :我在 C++/Java/C# 意義上使用術語“靜態”,因為它是與類型而非實例相關聯的字段/成員。 這並不意味着屬性/字段/成員是不變的、只讀的或不可變的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.