Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding JavaScript function unorthodoxy

I've been programming for the Web for quite some time now, but have only just recently discovered a few new intricacies regarding the use of functions and the weird (or so I view them as) things you can do with them. However, they seem at this point only to be syntactically pretty things. I was hoping somebody might enlighten me as to how some of these newly discovered aspects could prove to be useful.

For example, the first time I ran this, I thought for sure it would not work:

<script>
function x(q)
 {
q(x);
 }

x(function(a)
 {
alert(a);
 }
 );
</script>

But it did! Somehow, creating a named function which receives a different, anonymous function as its only parameter and then runs the function passed to it with itself passed as the parameter to it works just fine. This positively blew my mind and I'm almost certain there's a vast amount of practicality to it, but I just can't quite place it yet.

Ah, and another thing I was elated to discover: using a globally scoped variable to store a function, one can later in the execution use JavaScript's eval() function to modify that variable, thus changing the function's inner workings dynamically. An example:

<script>
var f = function()
 {
alert('old text');
 }

eval('f = ' + f.toString().replace('old text', 'new text'));

f();
</script>

Sure enough, that code alerts the "new text" string; when I saw that, my mind was once again blown, but also immediately intrigued as to the potential to create something incredible.

So... my burning question for Stack Overflow: how can such seemingly abstract coding principles be used in any positive way?

like image 813
Hexagon Theory Avatar asked Jan 26 '09 20:01

Hexagon Theory


1 Answers

What you're basically asking is How can I use functions as first-class objects?

The biggest and most common usage is closures (or anonymous functions) for event handling. However, just because you can be clever, it doesn't mean you should. Write clear, readable code just as you would in any other language.

Oh, and flog yourself for typing eval and never think about doing it again

like image 56
Kevin Avatar answered Nov 15 '22 12:11

Kevin