I am trying to implement (so-to-say) a refinement in JavaScript. Kindly look at the following example:
<html>
<head>
<title>Function Override (Refinement) example</title>
<script type="text/javascript">
// original function
function oneFunc() {
document.writeln("<p> In original oneFunc() </p>");
}
var prevOneFunc = null;
if (oneFunc) {
prevOneFunc = oneFunc;
}
// redeclared function (should refine/complement the original one)
function oneFunc() {
if (prevOneFunc) {
prevOneFunc(); // should call original oneFunc(), BUT IT ISN'T
}
document.writeln("<p> In refined oneFunc() </p>");
}
oneFunc();
</script>
</head>
<body>
</body>
</html>
My intention was to have two printouts:
In original oneFunc() In refined oneFunc()
However, it seems that since at the moment of execution oneFunc refers to the new/refined function, hence the output is different than expected. In the debugger checked that I am entering into the infinite recursion 🙂 (yes, understood why exactly).
Please explain which information I am missing to implement it properly.
Update: A few limitations: I think (not sure) that I can’t modify the original oneFunc declaration and it is declared just like described above. I shouldn’t modify the declaration of the refined oneFunc either.
That is because of JavaScript hoisting.
http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
Try this: