Skip to content

Instantly share code, notes, and snippets.

@podgorniy
Created March 31, 2012 15:29
Show Gist options
  • Save podgorniy/2266218 to your computer and use it in GitHub Desktop.
Save podgorniy/2266218 to your computer and use it in GitHub Desktop.
Safe javascript decorator
/*
Example of use
document.write = decorate (document.write, function () {
console.log(this === document);// true;
}, function () {
console.log('DOM is updated');
});
document.write = decorate (document.write, null, function () {
console.log('After document.write');
});
*/
function decorate (initial, decorate_before, decorate_after) {
var name;
function f () {
var initial_call_result;
try {
if (typeof decorate_before === 'function') {
decorate_before.apply(this, arguments);
}
} catch (err) {
if (mmcore.EH) {
mmcore.EH(err);
}
} finally {
initial_call_result = initial.apply(this, arguments);
}
try {
if (typeof decorate_after === 'function') {
decorate_after.apply(this, arguments);
}
} catch (err) {
if (mmcore.EH) {
mmcore.EH(err);
}
} finally {
return initial_call_result;
}
};
// try to copy props from original function to decorated one
// decorating may fail, if props are primitives
for (name in initial[name]) {
if (initial.hasOwnProperty(name)) {
f[name] = initial[name];
}
}
return f;
}
@podgorniy
Copy link
Author

Update for cases, when function object carries properties

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