javascript - 如何检查对象是否具有可以分配的属性?
问题描述
有没有一种简单的方法来检查对象是否具有可以分配的属性?
目前,我正在使用:
const obj = new MyClass();
if ('property' in obj) {
obj['property'] = value;
}
但是,如果MyClass
定义如下:
class MyClass {
get property() {
return 'value';
}
}
在这种情况下,property
确实存在,但不能分配给:
TypeError: Cannot set property quickRead of [object Object] which has only a getter
at eval (webpack-internal:///./lib/model/construct.ts:23:29)
at Array.forEach (<anonymous>)
at construct (webpack-internal:///./lib/model/construct.ts:16:27)
at new Subscription (webpack-internal:///./lib/model/subscription.ts:55:65)
at new Message (webpack-internal:///./lib/model/message.ts:40:5)
at Function.fromFirestore (webpack-internal:///./lib/model/message.ts:100:12)
at Function.fromFirestoreDoc (webpack-internal:///./lib/model/message.ts:114:29)
at eval (webpack-internal:///./lib/api/update/messages.ts:19:64)
at Array.filter (<anonymous>)
at updateMessages (webpack-internal:///./lib/api/update/messages.ts:16:26)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async Promise.all (index 0)
at async updateAccount (webpack-internal:///./pages/api/account.ts:55:5)
at async account (webpack-internal:///./pages/api/account.ts:88:7)
at async apiResolver (/home/ubuntu/repos/hammock/node_modules/next/dist/next-server/server/api-utils.js:8:1)
有没有办法可以使用in
关键字来检查是否可以分配属性?
解决方案
文档中的示例(注意writable
输出中的属性):
const object1 = {
property1: 42
};
const descriptor1 = Object.getOwnPropertyDescriptor(object1, 'property1');
//For class objects, we need to check for the objects prototype. If there is multilevel inheritance, then you will have to check prototypes one by one
const descriptor2= Object.getOwnPropertyDescriptor(Object.getPrototypeOf(object2), 'property1');
console.log(descriptor1);
descriptor1 将有很多键,在您的情况下一些更相关,例如 getter 和 setter。
推荐阅读
- google-app-engine - 实例需要很长时间才能启动
- asp.net-mvc - 更新 nuget 后 StackExchange.Redis.Extensions 错误
- c# - 由于代码中的切换行,存储过程切换参数
- web2py - Web2py:
(ImportError("无法导入模块'applications.*.modules.paramiko'",) - android - 显示带有 android 分页库的进度条
- javascript - 在传播语法 jn javascript 后使用分号会中断执行并出现错误“意外令牌 =”
- javascript - javascript - 返回最大累计利润
- c++ - .cpp 文件中的 C++ 静态对象声明
- mongodb - MongoDB 以特定时间间隔获取数据
- r - 将数据集子集到列表中