Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

paulirish commented Sep 12, 2013

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

This comment has been minimized.

Copy link

mattzeunert commented Mar 23, 2016

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