Sunday, August 28, 2005

Javascript function overriding, Part 3

In this installment, I will give you the code of how to prove what I have said.

To prove my point for method 1, create the following HTML page :

<html>
<body>

<script language="javascript">
var base_foo;

function foo()
{
alert('foo is called');
}

base_foo = foo;

function foo()
{
base_foo();
alert('override foo is called');
}

function clickme()
{
foo();
}
</script>

<input type="button" value="click me" onclick="clickme()"/>
</body>
</html>


If you click on the button, clickme() will be called which in turn call foo(), you will end up with a stack overflow exception.

This is because base_foo and foo point to the same memory address, when foo() call base_foo(), it is essentially a recursive function call.


To prove my point for method 2, create the following HTML page :

<html>
<body>

<script language="javascript">
var base_foo;

function foo(yourname)
{
alert('Hello ' + yourname);
}

base_foo = foo;

foo = function(yourname)
{
base_foo(yourname);
alert('(overide) Hello ' + yourname);
}


function clickme()
{
foo('Jonathan');
}
</script>

<input type="button" value="click me" onclick="clickme()"/>
</body>
</html>


If you click on the button, clickme() will be called which in turn will call foo(), what you will see now is 'Hello Jonathan' will be display, and then follow by '(override) Hello Jonathan'.

This show that base_foo and foo point to different memory address.

In the next final part of this series, I will give you a scenario when the 2 method will make a difference and a case study where I have use method 2 to override function.

Labels:

4 Comments:

At 8:06 PM, Blogger Anders Kjellerup Jacobsen said...

Really helpfull :)

 
At 8:07 PM, Blogger Anders Kjellerup Jacobsen said...

Really helpfull :)

 
At 6:31 AM, Blogger Adam said...

Thanks for the post, you showed me how to do exactly what I need to do.

 
At 10:33 PM, Blogger Unknown said...

That right there was exactly what I was after, thanks.

 

Post a Comment

<< Home