我有这样的代码:

class Category {
  constructor(
    readonly _title: string,
  ) { }

  get title() {
    return this._title
  }
}

 type Categories = typeof categories

 const categories = {
  get pets() {
    return new class extends Category {
      constructor() {
        super(
          'Pets',
        )
      }

      get dishes() {
        return new Category(
          'Pets dishes',
        )
      }
    }
  },
  get cloth() {
    return new class extends Category {
      constructor() {
        super(
          'Cloth',
        )
      }

      get accessories() {
        return new Category(
          'Accessories',
        )
      }
    }
  },
}

Object.entries(categories).forEach(([, category]) => {
  // Actual logs:
  // ["_title"]
  // ["_title"]
  // Expected logs: 
  // ["dishes"]
  // ["accessories"]
  console.log(Reflect.ownKeys(category))
})

为什么Reflect.ownKeys返回的结果与我预期的不同? 如何获得获得者名单?

推荐答案

dishesaccessories不是own处房产.它们是在匿名类的原型上定义的属性.另一方面,_titleis是所创建对象的拥有属性,因为该属性是由构造函数(经由Category的构造函数中的超级调用)添加的.

如果您只想得到dishesaccessories的结果,那么迭代原型:

  console.log(Reflect.ownKeys(Object.getPrototypeOf(category))
                     .filter(prop => prop !== 'constructor'));

Javascript相关问答推荐

使用print This时, map 容器已在LeafletJS中初始化

如何判断属于多个元素的属性是否具有多个值之一

为什么!逗号和空格不会作为输出返回,如果它在参数上?

我怎么才能得到Kotlin的密文?

如何控制Reaction路由加载器中的错误状态?

Angular 订阅部分相互依赖并返回数组多个异步Http调用

使用原型判断对象是否为类的实例

如何修复我的数据表,以使stateSave正常工作?

为什么123[';toString';].long返回1?

使用NextJS+MongoDB+Prisma ORM获取无效请求正文,无法发布错误

变量在导入到Vite中的另一个js文件时成为常量.

在表单集中保存更改时删除';禁用';

在Vercel中部署Next.js项目时获取`ReferenceError:未定义文档`

如何通过Axios在GraphQL查询中发送数组

在HTML5画布上下文中使用putImageData时,重载解析失败

如何使用Reaction路由导航测试挂钩?

TypeORM QueryBuilder限制联接到一条记录

KeyboardEvent:检测到键具有打印的表示形式

使用VITE开发服务器处理错误

如何格式化API的响应