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

Solution 1:

I think you're looking for getOwnPropertyDescriptor?

Solution 2:

You can use Object.getOwnPropertyDescriptor(obj, prop)

For example:

var obj = { first: 1 }
obj.__defineGetter__('second', function() { return 2; });

// get descriptors
var descriptor1 = Object.getOwnPropertyDescriptor(obj, 'first');
var descriptor2 = Object.getOwnPropertyDescriptor(obj, 'second');

// check if it's a getter

descriptor2.get
// returns function () { return 2; }

descriptor1.get
// returns undefined

Solution 3:

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