perial 😮amused

Javascript madness

Just found out a freaky thing about Javascript. Not only does each function have an argument.object that includes a callee field containing the function itself (allowing anonymous recursive functions), you can rewrite it. The code behind the cut defines a function that always makes a recursive call at the end, except to escape it rewrites its own identity. Tee-hee:)

<html>
<head>
<title>Rewriting anonymous recursive functions</title>
</head>
<body>
<div id="foo"></div>
<script type="text/javascript">
var div = document.getElementById("foo");
var rec = function(x) {
  if (x > 10) {
    arguments.callee = function(x) {
      div.appendChild(document.createTextNode("" + x));
    }
  }
  arguments.callee(x + 2);
}
rec(1);
</script>
</body>
</html>