Skip to content

Instantly share code, notes, and snippets.

@dmethvin
Created January 25, 2012 13:51
Show Gist options
  • Star 51 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • 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;
}
});
};
@paulirish
Copy link

Usage

Omg the cookie is being changed, but where? Give me a breakpoint when JS changes my cookies!

debugAccess(document, 'cookie');

Some JS is getting the scrollTop value causing massive Recalculate Styles costs.. Who is the perpetrator?

debugAccess(document.body,'scrollTop', true)

@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