首页 > 解决方案 > 如何检查对象是否具有可以分配的属性?

问题描述

有没有一种简单的方法来检查对象是否具有可以分配的属性?

目前,我正在使用:

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关键字来检查是否可以分配属性?

标签: javascript

解决方案


使用getOwnPropertyDescriptor

文档中的示例(注意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。


推荐阅读