Object.getOwnPropertyDescriptors()
靜態方法 Object.getOwnPropertyDescriptors() 返回給定物件的所有自身屬性描述符。
試一試
const object = {
foo: 42,
};
const descriptors = Object.getOwnPropertyDescriptors(object);
console.log(descriptors.foo.writable);
// Expected output: true
console.log(descriptors.foo.value);
// Expected output: 42
語法
js
Object.getOwnPropertyDescriptors(obj)
引數
obj-
要獲取所有自身屬性描述符的物件。
返回值
一個包含物件所有自身屬性描述符的物件。如果沒有屬性,可能是一個空物件。
描述
此方法允許檢查物件所有自身屬性的精確描述。JavaScript 中的屬性由一個字串名稱或一個 Symbol 和一個屬性描述符組成。有關屬性描述符型別及其屬性的更多資訊,請參閱 Object.defineProperty()。
屬性描述符是一個包含以下部分屬性的記錄
示例
建立淺複製
雖然 Object.assign() 方法只會將源物件的可列舉和自身屬性複製到目標物件,但您可以使用此方法和 Object.create() 在兩個未知物件之間實現 淺複製。
js
Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj),
);
建立子類
建立子類的典型方法是定義子類,將其原型設定為超類例項,然後在該例項上定義屬性。這可能會很麻煩,尤其是對於 getter 和 setter。相反,您可以使用此程式碼設定原型。
js
function superclass() {}
superclass.prototype = {
// Define the superclass constructor, methods, and properties here
};
function subclass() {}
subclass.prototype = Object.create(superclass.prototype, {
// Define the subclass constructor, methods, and properties here
});
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-object.getownpropertydescriptors |
瀏覽器相容性
載入中…