Occasionally when using javascript you’ll find that you want to intercept a function call, usually to run some code before invoking functions belonging to a third-party codebase. Essentially, this is achieved by saving a reference to the original function and then replacing it with a new function which, at the end, calls the original. Something like:

(function () {
    var originalFunction = Object.getPrototypeOf(someObject).someFunction;
    Object.getPrototypeOf(someObject).someFunction = function () {
        // intercept code here
        originalFunction.call(this);
    }
})();

Likewise, interception is possible if a property has a getter or a setter:

(function() {
    var propDesc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(someObject), "someProperty"),
        originalGetter = propDesc.get,
        originalSetter = propDesc.set;

    propDesc.set = function(val) {
        // getter intercept code here
        return originalSetter.call(this, val);
    };

    propDesc.get = function() {
        // setter intercept code here
        return originalGetter.call(this);
    };

    Object.defineProperty(Object.getPrototypeOf(someObject), "someProperty", propDesc);
})();

As you can see this is basically the same; the only real difference is that you need to use Object.getOwnPropertyDescriptor / Object.defineProperty rather than being able to set it directly using regular assignment. This is because var getter = someObject.someProperty will return the result of the getter function, and someObject.someProperty = "something" will invoke the setter function.

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks

4 thoughts on “Intercepting Properties with Getters/Setters

  1. Thanks for the great article!

    Was stuck with intercepting accesses for prototypes and your article just saved my life. Really smart to store the getter & setters and invoke them with “this.”

    I wonder if it’s possible to intercept calls when the property doesn’t have a getter or setter.

    Reply
  2. This blog is really interesting, but why it is on 14th place in google’s search
    results. It deserves to be in top 5. Many
    webmasters think that seo is dead in 2016, but it is not true.
    There is sneaky method to reach google’s top 5 that not many people know.
    Just search for: pandatsor’s tools

    Reply

Leave a reply

required

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>