views:

569

answers:

3

A few days ago, I asked a question regarding dynamically modifying a function's code midway through the outerlying script's execution and I was told to completely forget ever coming upon the notion. I'm not sure I understand why that is. Let me give an example:

<script>
var display = function(msg)
 {
alert(msg);
 }

// Now, at the moment, the display() function
// is receiving a single parameter and alerting
// it to the user. I'm now going to use eval()
// to modify the display() function.

eval('display = ' + display.toString().replace('alert(', 'document.write('));

// Now, the display() function writes its parameter
// to the document as opposed to alerting it.
</script>

I realize this is a rather trivial example, but there must surely be some use that can be derived from being able to dynamically modify a function, something so useful by itself.

A: 

Well, using eval might be a security concern but modifying a function in real-time is ok. How else you can make memoization anyway?

Although, come to think of it, changing method signature isn't a great idea, other people won't know how to call this function after this, since it would depend on execution order and it's not easy to track usually.

vava
+4  A: 

There are cases where it could be useful to change a function's behavior, but there are better ways to do it. In your example, you could create new instances of the function that handle the output differently, by passing a function as an argument (similar to the strategy pattern):

function makeDisplay(displayStrategy) {
    return function(msg) {
        // I'm assuming you would do some additional processing here...

        displayStrategy(msg);
    }
}

var display = makeDisplay(alert);

// now modify display to use document.write
display = makeDisplay(function(msg) { document.write(msg); });
Matthew Crumley
+4  A: 

Although this may do what you need it to do, 6 months from now you (or the person maintaining your code) will be going "WTF?!"

If your use case is to alert or write based on some condition, why don't you write two different functions? Or have your function take another parameter that decides the output mode. Or pass in a function as a parameter that performs the actual output. Something, you know, a little more on the sane side. ;-)

davogones