when do you use Object.defineProperty()

前端 未结 10 2351
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 01:31

I\'m wondering when I should use

Object.defineProperty

to create new properties for an object. I\'m aware that I\'m able to set things lik

10条回答
  •  一向
    一向 (楼主)
    2020-12-08 02:27

    One neat use case I have seen for defineProperty is for libraries to provide an error property to the user which, if it's not accessed within a certain interval you would throw yourself. For example:

    let logErrorTimeoutId = setTimeout(() => {
      if (error) {
        console.error('Unhandled (in )', error.stack || error);
      }
    }, 10);
    
    Object.defineProperty(data, 'error', {
        configurable: true,
        enumerable: true,
        get: () => {
          clearTimeout(logErrorTimeoutId);
          return error;
        },
      });
    

    Source for this code: https://github.com/apollographql/react-apollo/blob/ffffd3d8faabf135dca691d20ce8ab0bc24ccc414e/src/graphql.tsx#L510

提交回复
热议问题