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 modify the framework itself.

Comments

Avatar

Anonymous on 2012-04-23 07:01 reply

Function Redefining

JS provides a very smart way to redefine a function. You need to write a anonymous function and assign it to a variable and redefine your function inside the body.
In that case when you will call myFunc. First time your original function will be executed and second time your redefined function will be executed means first function would be overwrite by redefined function.

var myFunc = function()
{
alert(" I am first call");
myFunc = function()
{
alert("I am redefined function call");
}
}
myFunc();// First call
myFunc()// Second Call

Avatar

Spinx Inc. on 2013-03-25 05:57 reply

Redefining functions in JavaScript

Yeah, by using JavaScript, you can redefine the function. You just need to create the function and assign that function to the variable. After the completion of the code of function, you need to call the function in the body. Here, you have shared useful method. Good to see your post.

Comment Atom Feed