Reflection on JS

By Raúl on Mar 8, 2023
Image courtesy of unsplash

More frequent than not, I ended up throwing some good and old school console.log statements that help me during debugging.

That is OK, but it might become cumbersome when more than a couple are necessary.

Leveraging on reflection is a nice technique to save us from having to writing them explicitly.

By returning the following code as the end of a class constructor I can get console.log for every function invoked, using JS reflection.

return new Proxy(this, {
      get: function(target, name, receiver) {
        if (!target.hasOwnProperty(name)) {
          if (typeof target[name] === 'function') {
            console.log(
              target.constructor.name,
              '::',
              name
            );
          }
          return new Proxy(target[name], this);
        }
        return Reflect.get(target, name, receiver);
      },
    });
2024. Personal website built with Astro & Streamline.