Determine if a JavaScript property has a getter or setter defined?

前端 未结 5 2045
刺人心
刺人心 2020-12-01 09:58

Is it possible, given an object and property name to determine if that property is defined using either a getter or setter, or is it completely transparent? I only want to d

5条回答
  •  情深已故
    2020-12-01 10:46

    You can use Object.getOwnPropertyDescriptor(obj, prop).

    function isGetter (obj, prop) {
      return !!Object.getOwnPropertyDescriptor(obj, prop)['get']
    }
    

    Usage:

    obj = {
      foo: 'foo',
      get bar() { return 'bar' }
    }
    
    isGetter(obj, 'bar') // will return true
    isGetter(obj, 'foo') // will return false
    

提交回复
热议问题