【发布时间】:2022-01-11 07:39:46
【问题描述】:
我试图让我的类表现得像一个“正常”对象,因为当它在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))
【问题讨论】:
标签: javascript node.js oop