Breakpoint on access to a property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}); | |
}; |
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
Usage