In Javascript, how to display the function body of a setter/getter?

612 views Asked by At

For example (from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set), I init an object like this:

var o = {
  set current (str) {
    this.log[this.log.length] = str;
  },
  log: []
}

How can I print the function body of o.current in console? If o.current is a plain method, it can be done by o.current.toString().. However, I have no idea about how to print the function body of a "getter" or "setter" method.

Does anyone have ideas about this?

1

There are 1 answers

0
k-nut On BEST ANSWER

You can use __lookupSetter__ for this. So simply calling o.__lookupSetter__('current').toString() should give you your desired output. Source

Update

This is already deprecated though. You should be using the standard Object.getOwnPropertyDescriptor instead. So calling Object.getOwnPropertyDescriptor(o, 'current').set.toString() will work for your use case. Source