Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 225
Hanfei Sun Avatar asked Oct 26 '25 10:10

Hanfei Sun


1 Answers

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

like image 63
k-nut Avatar answered Oct 27 '25 23:10

k-nut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!