Friday, August 26, 2005

Javascript function overriding, Part 2

Continue from the part 1, I will give a more detail explaination to what I say in Part 1.

Using the same example :
Method 1
<script language="javascript">
var base_foo;

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

base_foo = foo;

function foo()
{
alert('override foo is called');
}
</script>

The first time you create function foo(), your code will be loaded into a arbitary memory location, say for example 0x001a.

Your function pointer foo will be set to point to address 0x001a.

Next you assign base_foo to point to the same memory address pointed to by foo

Now, your override function foo() to do different thing. The script engine will load your new code into the same memory location (0x001a).

And both your function pointer foo and base_foo will remain point to the same address.


Moving to method 2:
Method 2
<script language="javascript">
var base_foo;

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

base_foo = foo;

foo = function(yourname)
{
alert('(overide) Hello ' + yourname);
}
</script>


The first time you create function foo(), your code will be loaded into a arbitary memory location, say for example 0x001a.

Your function pointer foo will be set to point to address 0x001a.

Next you assign base_foo to point to the same memory address pointed to by foo.

Now you override function foo() to do different thing:

foo = function(yourname)
{
// your new code
}

What happen now is your new code is loaded into a new memory location, say (0x002a).

Your function pointer foo will now be changed to point to address 0x002a. But base_foo remain point to 0x001a.

In the next part, I will give an example of how to prove this.

Labels:

1 Comments:

At 6:39 PM, Anonymous Anonymous said...

Hi your explanation was very helpful to me. Thnx. Keep writing....

 

Post a Comment

<< Home