Skip to content

Instantly share code, notes, and snippets.

@dmethvin
Created January 25, 2012 13:51
Show Gist options
  • Save dmethvin/1676346 to your computer and use it in GitHub Desktop.
Save dmethvin/1676346 to your computer and use it in GitHub Desktop.
Breakpoint on access to a property
function debugAccess(obj, prop, debugGet){
var origValue = obj[prop];
Object.defineProperty(obj, prop, {
get: function () {
if ( debugGet )
debugger;
return origValue;
},
set: function(val) {
debugger;
return origValue = val;
}
});
};
@mattzeunert
Copy link

The snippet above makes property assignments lose their side effects (e.g. document.body.scrollTop controlling the scroll position on the page).

You can use this code to call through to the original getter/setter functions.

function debugAccess(object, prop, debugGet){
    var originalProp = getPropertyDescriptor(object, prop);
    var isSimpleValue = "value" in originalProp; // rather than getter + setter

    Object.defineProperty(object, prop, {
        get: function(){
            if (debugGet) {
                debugger;
            }
            if (isSimpleValue) {
                return originalProp.value;
            } else {
                return originalProp.get.apply(this, arguments);    
            }
        },
        set: function(newValue){
            debugger;
            if (isSimpleValue) {
                return originalProp.value = newValue;
            } else {
                return originalProp.set.apply(this, arguments);
            }
        }
    });

    function getPropertyDescriptor(object, propertyName){
        var descriptor = Object.getOwnPropertyDescriptor(object, propertyName);
        if (!object){
            throw new Error("Descriptor " + propertyName + " not found");
        }
        if (!descriptor) {
            return getPropertyDescriptor(Object.getPrototypeOf(object), propertyName);
        }
        return descriptor;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment