Tag: javascript ¦ Atom ¦ RSS

Redefining functions in Javascript

A few days ago I wanted to know how easy it is to redefine a function in Javascript which is already defined. I know that doing something similar in Ruby is rather easy and I had the feeling that it would be possible in Javascript as well.

After some googling and testing I came up with the following test document (which is perfectly valid HTML5 btw!):

<!DOCTYPE html>
<title>foo</title>
<script type="text/javascript">
  function foobar() {
    window.alert('hello');
  }

  oldfoobar = foobar;

  foobar = function() {
    window.alert('hello overwritten');
    oldfoobar();
  }

  foobar();
</script>

I'm not sure if this is the 'javascript-way' of doing things, but it works. First I defined the function foobar(), which simply shows a 'hello' alertbox. Then I redefined that same method to first display another alert, and then call the original function, which will still show the 'hello' alertbox.

While the example is not very useful, this technique could be useful to redefine a method of some framework to attach custom logic (such as logging) without having to …