我試圖讓我的類表現得像一個“普通”物件,因為當它被呼叫時,object.entries它回傳一個鍵值對陣列。經過相當多的搜索,我已經能夠使我的類可迭代。但我找不到從實施方面開始的地方object.entries。
這就是我要達到的地方,
'use strict'
class Person {
#name
constructor(name) {
this.#name = name
}
get name () {
return this.#name
}
*iterator () {
var props = Object.getOwnPropertyNames(Object.getPrototypeOf(this))
for (const prop of props) {
if (typeof this[prop] !== 'function') {
const o = {}
o[prop] = this[prop]
yield o
}
}
}
[Symbol.iterator] () {
return this.iterator()
}
}
const person = new Person ('bill')
//works - produces { name: 'bill' }
for (const prop of person){
console.log (prop)
}
// doesn't work. Prints an empty array
console.log (Object.entries(person))
uj5u.com熱心網友回復:
問題是您的實體沒有公共的“自己的”(不是繼承的)屬性,這是Object.entries其陣列中包含的內容。
我試圖讓我的類表現得像一個“普通”物件,因為當它在 object.entries 中被呼叫時,它回傳一個鍵值對陣列。
這是默認行為,無論您是通過類建構式還是其他方式創建物件。
經過相當多的搜索,我已經能夠使我的類可迭代。
Object.entries 與物件是否可迭代無關。
我不認為您可以在不創建“自己的”資料屬性的情況下獲得Object.entries回報。但是您可以通過以下方式使其成為只讀的自己的資料屬性:[[name, "value"]]nameObject.defineProperty
class Person {
#name;
constructor(name) {
this.#name = name;
Object.defineProperty(this, "name", {
value: name,
writable: false,
enumerable: true,
configurable: true
});
}
}
const bill = new Person("Bill");
console.log(`bill.name:`, bill.name);
console.log(`Object.entries(bill):`, Object.entries(bill));
我一直#name留在那里,但可能沒有理由這樣做,所以:
顯示代碼片段
class Person {
constructor(name) {
Object.defineProperty(this, "name", {
value: name,
writable: false,
enumerable: true,
configurable: true
});
}
}
const bill = new Person("Bill");
console.log(`bill.name:`, bill.name);
console.log(`Object.entries(bill):`, Object.entries(bill));
如果您希望能夠在name內部進行設定,只需給自己一個重復的私有方法defineProperty:
class Person {
constructor(name) {
this.#setName(name);
}
#setName(name) {
Object.defineProperty(this, "name", {
value: name,
writable: false,
enumerable: true,
configurable: true
});
}
}
const bill = new Person("Bill");
console.log(`bill.name:`, bill.name);
console.log(`Object.entries(bill):`, Object.entries(bill));
不幸的是,由于該屬性是可配置的,因此您的代碼并不是唯一可以defineProperty用來更改它的代碼。(這很像name函式上的屬性,默認情況下是只讀的,但可以通過 更改defineProperty。)所以它與擁有#nameand并不完全相同get name,它只是在提供對Object.entries.
uj5u.com熱心網友回復:
您實際上不必實作迭代器。Object.entries不起作用的原因是由于#該財產被視為私有財產,因此不予退還。如果您洗掉 ,# name則回傳Object.entries如下例所示。
class Person {
name
constructor(name) {
this.name = name
}
}
const person = new Person ('bill')
// doesn't work. Prints an empty array
console.log(Object.entries(person))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/408217.html
標籤:
