Function Defined In Debug Mode Immediately Disappears
Solution 1:
It seems that the debugger discards functions that were defined using the format function foo() {}
, but keeps functions that were defined using the format foo = function() {}
.
Solution 2:
How can I use it?
Method 1: First load the page, then run the snippet.
Method 2: define the function breakOn
as a variable (anonymous function expression) if you want to successfully define it while a breakpoint is active (pointed out by 'root')
var breakOn = function (obj, propertyName, mode, func) {
// this is directly from https://github.com/paulmillr/es6-shimvar getPropertyDescriptor = function (obj, name) {
var property = Object.getOwnPropertyDescriptor(obj, name);
var proto = Object.getPrototypeOf(obj);
while (property === undefined && proto !== null) {
property = Object.getOwnPropertyDescriptor(proto, name);
proto = Object.getPrototypeOf(proto);
}
return property;
}
var verifyNotWritable = function() {
if (mode !== 'read')
throw"This property is not writable, so only possible mode is 'read'.";
}
var enabled = true;
var originalProperty = getPropertyDescriptor(obj, propertyName);
var newProperty = { enumerable: originalProperty.enumerable };
// writeif (originalProperty.set) {// accessor property
newProperty.set = function(val) {
if(enabled && (!func || func && func(val)))
debugger;
originalProperty.set.call(this, val);
}
} elseif (originalProperty.writable) {// value property
newProperty.set = function(val) {
if(enabled && (!func || func && func(val)))
debugger;
originalProperty.value = val;
}
} else {
verifyNotWritable();
}
// read
newProperty.get = function(val) {
if(enabled && mode === 'read' && (!func || func && func(val)))
debugger;
return originalProperty.get ? originalProperty.get.call(this, val) : originalProperty.value;
}
Object.defineProperty(obj, propertyName, newProperty);
return {
disable: function() {
enabled = false;
},
enable: function() {
enabled = true;
}
};
};
E.g. enter breakOn(document.body, 'clientWidth', 'read')
in the console (or at the end of the snippet), continue code execution if at a breakpoint,
then access (read) the property 'clientWidth' of the document.body object in the console with document.body.clientWidth
.
This should make the snippet code stop at the debugger statement. Now the call stack can be used to see who or what changed the property, in this case 'anonymous'.
Post a Comment for "Function Defined In Debug Mode Immediately Disappears"