Created
March 31, 2012 15:29
-
-
Save podgorniy/2266218 to your computer and use it in GitHub Desktop.
Safe javascript decorator
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
/* | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update for cases, when function object carries properties