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.

comments powered by Disqus