3 ways of creating functions in javascript
In javascript, all functions are an instance of the class Function (with a capitalized F).
The old way
Everybody knows how to do it. In fact most languages do it this way. Boring but you can’t write javascript without knowing it.
[source:javascript]
function f() {
}
[/source]
The uppercase F way
You can directly create an instance of the Function class this way.
[source:javascript]
var f = new Function(”alert(’Function called’);”);
f();
[/source]
The problem with that is that the code of the class is passed as a parameter of the constructor. A lot of people use this method to create “dynamic” functions but they do just because they don’t know of the lowercase f way of doing it.
[source:javascript]
var i = 100;
// “dynamically” alert the i variable
var alertNumber =new Function(”alert(’Number is ” + i + “‘);”);
alertNumber();
[/source]
It looks bad for such a simple example. It gets uglier as it gets more complex. Please, don’t use this method.
The lowercase f way
This one is the one you’re looking for. Why? Because it is as handy as the uppercase F but you don’t have to write the code as a string. Example, I dynamically load an image and I want to alert when the image is ready.
[source:javascript]
var img = new HtmlImage();
img.src=”…”;
var onLoadFunction = function() {
alert(”Image is ready!”);
}
img.onload = onLoadFunction;
[/source]
But wait!
As I was writing this, I realized something that I didn’t realize before. The old way of writing functions is not as boring as I thought.
[source:javascript]
function parent() {
function child() {
alert(”Child function called”);
}
// Assign the function to a variable
var childFunction = child;
childFunction();
}
parent();
[/source]
Executing above code will alert “Child function called”. So, javascript also creates a variable called child when I write function child() {}. Interesting.


RSS without the echo chamber
[…] javascript, all functions are an instance of the class Function (with a capitalized […]
Your so called “lowercase f way” is properly refered to as an anonymous function, while your “uppercase F way” is the creation of a function through a constructor. You’re “old way is probably best refered to ask a traditional function. Fancy that.
Thanks Chris. I took a look at your site. Happy to see that I’m not the only one working to make javascript a better place.
I used simple terms to make the distinction because not everyone is familiar with the more technical terms. But I have to admit that I should have referenced them… I will as soon as possible.
Dan, there is one bit of code I don’t understand.
1. var i = 100;
2. // “dynamically” alert the i variable
3. var alertNumber(”alert(’Number is ” + i + “);”);
What is “alertNumber” exactly? I’m confused as it’s kind of came out from nowhere.
Is it an instance of the “Function” class?
Frank, my mistake.
var alertNumber(â€alert(’Number is †+ i + “);â€);
was changed to
var alertNumber = new Function(”alert(’Number is ” + i + “‘);”);
In your Function example, you concatenate the value of the variable i into the string. And the value it had at that time remains permanently. I haven’t found any other good way to write that sort of thing other than as a new Function.
In your function example, the code is static — there is no code generated which could differ depending on the situation.
Steve, I suggest that you take a look at closures. It could solve your two problems.
var i = 10; fct = function() { alert(i); } fct();Hmmm, I’m trying to figure out if they will help. I have heard that they use up a lot of memory, and it seems like I would need to keep a lot of objects hanging around if I want to use this multiple times.
The basic problem I have is that I’ve got a page with what Access calls “continuous forms” (I call it a paper towel page, because there are a series of identical forms, each one displaying one record).
I’ve switched to using AJAX, so I need to rewrite the page and insert a node with a new form each time a record is added. There is a blank form at the end for this purpose. When its save button is clicked, the div node holding the form is cloned, and I copy the element contents to the new elements (interesting that a “deep” clone doesn’t do this …).
Then I rename and re-id each element. The problem comes in assigning the event handlers, since I’ve got to do it in a
frm[”saveButton”].onclick = …
fashion, and the code has to use the id field value that came back with the XML response (note that the response is true XML, not HTML, which would make life easier since the script could be written with the ids embedded at the server end).
For actual form elements, that works fine, because the id value is stored in a hidden field in the form, so I can use a function() { … } approach, since the code is plain text (using frm.id.value to get the id). But, for example, an image clicked to collapse or expand the div can’t reference the form easily; I’d have to go backing up the node tree and coming down into the form.
So, I use:
imgShowHide.onclick = new Function(”toggleDisplay(” + intId + “);”);
Once the string is generated, that id value stays with the function and is protected from any changes.
Since you get the information as XML, you necessarily have to parse it using JS. What you then could do is something like:
var myImg=document.createElement(”img”)
img.src=”mistigri.jpg”
img.refForm=document.forms[0]
img.save=function(){this.refForm.save.click()}
img.onclick=this.save;
Yeah, I like that approach — by making the form a property of the image, I get a the processing of the id value over and done with before I actually generate the function code. That approach would also streamline a few other things going on in my app.