473,574 Members | 2,220 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

An Introduction to Function Objects

pbmods
5,821 Recognized Expert Expert
AN INTRODUCTION TO FUNCTION OBJECTS
LEVEL: INTERMEDIATE
PREREQS: OBJECTS

You've seen it before. You're setting up an XMLHttpRequest call, and you need to execute a function when it returns, so you do something like this:

Expand|Select|Wrap|Line Numbers
  1. http.onreadystatechange = myAwesomeFunction;
  2.  
This works really well for awhile. But soon you get to wondering if it's possible to execute more than one function when http's readystate changes. Or maybe you need to pass some extra parameters to myAwesomeFuncti on.

You read somewhere that you can do this:

Expand|Select|Wrap|Line Numbers
  1. var width = 100, height = 300;
  2. http.onreadystatechange = function() {
  3.     myAwesomeFunction();
  4.     doSomethingAmazing(width, height);
  5. };
  6.  
That works great, but you can't help but wonder why.

Well, here's why:

All functions in JavaScript are actually objects.

That's right. A function is an object, just like window, or document, or 2, or 'Hello, World!', or....

If you're familiar with JavaScript objects, you probably know that scalars are objects. For example:

Expand|Select|Wrap|Line Numbers
  1. var myNumber = 2;
  2. var myNumber = new Number(2);
  3.  
  4. var myString = 'Hello!';
  5. var myString = new String('Hello!');
  6.  
  7. var myBoolean = true;
  8. var myBoolean = new Boolean(true);
  9.  
and so on. Note that in each pair, you are using the 'literal' value in the first statement. Both statements in each pair, however, produce identical results.

So if numbers and booleans and other types that we take for granted are all objects, why not functions?

Expand|Select|Wrap|Line Numbers
  1. function doSomething(x, y) {
  2.     return x * y;
  3. }
  4.  
  5. var doSomething = new Function('x, y', 'return x * y;');
  6.  
Amazingly, both statements will run in your favorite browser, and they will produce identical results*!

Ok, so functions are objects. So what?

Well, let's go back to the XMLHttpRequest snippet above:

Expand|Select|Wrap|Line Numbers
  1. http.onreadystatechange = myAwesomeFunction;
  2.  
Unlike in, for example, PHP where myAwesomeFuncti on resolves to a string, which the Zend engine determines to be the name of a defined function, JavaScript is actually using the Function object stored directly in the variable named myAwesomeFuncti on.

Similarly to how you could assign myVar a value of 2 like this:
Expand|Select|Wrap|Line Numbers
  1. var someObject = new Number(2);
  2.  
  3. myVar = someObject;
  4.  
... you could assign http.onreadysta techange a 'value' of a function like this:
Expand|Select|Wrap|Line Numbers
  1. var someObject = new Function('', 'alert("Hi!");');
  2.  
  3. //    Or...
  4. function someObject() {
  5.     alert("Hi!");
  6. }
  7.  
  8. http.onreadystatechange = someObject;
  9.  
Pretty neat, huh? But there's more!

Remember how you were able to store multiple functions to http.onreadysta techange by doing this:

Expand|Select|Wrap|Line Numbers
  1. var width = 100, height = 300;
  2. http.onreadystatechange = function() {
  3.     myAwesomeFunction();
  4.     doSomethingAmazing(width, height);
  5. };
  6.  
Why does that work?

Remember how we created a function using the Function constructor:

Expand|Select|Wrap|Line Numbers
  1. function callSomeFuncs() {
  2.     myAwesomeFunction(response);
  3.     doSomethingAmazing(width, height);
  4. }
  5.  
  6. //    Which is equivalent to this:
  7. var callSomeFuncs = new Function('', 'myAwesomeFunction(response);\ndoSomethingAmazing(width, height);');
  8.  
  9. //    In both cases, we can assign http.onreadystatechange the 'value' (function object) of doSomething like this:
  10. http.onreadystatechange = doSomething;
  11.  
But shouldn't this work, too?

Expand|Select|Wrap|Line Numbers
  1. http.onreadystatechange = new Function('', 'myAwesomeFunction(response);\ndoSomethingAmazing(width, height);');
  2.  
  3. //    Remember that these work:
  4. var myNumber = new Number(2);
  5. var myString = new String('Hello!');
  6. var myBoolean = new Boolean(true);
And if we translate that so that we can use the function keyword:
Expand|Select|Wrap|Line Numbers
  1. http.onreadystatechange = function() {
  2.     myAwesomeFunction(response);
  3.     doSomethingAmazing(width, height);
  4. }
  5.  
Hey, look at that!

Incidentally, this is an example of what we like to call an 'anonymous function', since we're not defining it with a variable name to the right side of the function keyword.

But that doesn't mean that our function disappears!

Expand|Select|Wrap|Line Numbers
  1. http.onreadystatechange = function() {
  2.     alert('Hi!');
  3. }
  4.  
  5. http.onreadystatechange();
  6.  
Can you guess what this code does? That's right; it creates an alert! It doesn't matter what variable stores your function object; all you have to do is put some parenthesis after the variable name, and the browser will execute the function stored in that variable.

One more:
Expand|Select|Wrap|Line Numbers
  1. var myFoo = function() {
  2.     alert('Hi!');
  3. }
  4.  
  5. var someBar = myFoo;
  6.  
  7. someBar();
  8.  
  9. //    Why does this work?  Well, for the same reason that this works, but instead of calling the function stored in someBar, this code passes the value stored in someBar (2) to the function stored in document.write.
  10. var myFoo = new Number(2);
  11.  
  12. var someBar = myFoo;
  13.  
  14. document.write(someBar);    //    Outputs '2'.
  15.  
So now you know JavaScript's dirty little secret. All functions are actually objects.

For more information, take a look at the MDC JavaScript Reference

*[SIDEBAR: Actually, the second statement will execute a tiny fraction of a second more slowly because explicitly-defined functions (using the 'Function' constructor) are interpreted rather than compiled. So you should try to use the function keyword rather than explicitly creating Function objects wherever possible.]
May 29 '07 #1
3 9251
acoder
16,027 Recognized Expert Moderator MVP
Excellent article. It's well-written and I like it!

We needed some articles here. This is a good start.
May 30 '07 #2
sumittyagi
202 Recognized Expert New Member
pbmods!! its really a great effort.
Your article is really great.
and the link you provided is invaluable.

Thanks a lot for such a nice article and keep it up.
May 31 '07 #3
pbmods
5,821 Recognized Expert Expert
Hey thanks for the feedback!

I did find myself posting this stuff in a lot of threads, so I figured it was time to condense it and article it.
May 31 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

14
2814
by: Alf P. Steinbach | last post by:
Not yet perfect, but: http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01_examples.zip To access the table of contents, use the "Bookmarks" tab in Adobe Acrobat. Comments, corrections, praise, nits, etc., are still welcome!
13
2733
by: Xah Lee | last post by:
there's this one i can't figure out. I'm trying to kick out image.google.com's top frame when it goes to my page. If you go to http://images.google.com/images?q=milk+tits click on the page http://xahlee.org/Periodic_dosage_dir/20031016_caryatids.html it should kick out the google's frame, but it isn't.
12
1913
by: Xah Lee | last post by:
Frameset Infinity! http://xahlee.org/js/frame2/frameset.html HTML Frame tutorial + Infinity! http://xahlee.org/js/frame/0.html Xah xah@xahlee.org ∑ http://xahlee.org/
7
1653
by: Jeremy Sanders | last post by:
Here is a brief simple introduction to Python I wrote for a computing course for graduate astronomers. It assumes some programming experience. Although it is not a complete guide, I believe this could be a useful document for other groups to learn Python, so I'm making it available for others to download, and modify for their own needs (some...
12
3573
by: Xah Lee | last post by:
Of Interest: Introduction to 3D Graphics Programing http://xahlee.org/3d/index.html Currently, this introduction introduces you to the graphics format of Mathematica, and two Java Applet utilities that allows you to view them with live rotation in a web browser. Also, it includes a introductory tutorial to POV-Ray.
5
1832
by: piyush | last post by:
void swap(int *p,*q) { int t; t=*p; *p=*q; *q=t; } coresponding call statement x=4; y=5;
5
6269
by: r035198x | last post by:
Setting up. Getting started To get started with java, one must download and install a version of Sun's JDK (Java Development Kit). The newest release at the time of writting this article is JDK 6 downloadable from http://java.sun.com/javase/downloads/index.jsp. I will be using JDK 5(update 8)
0
5324
RedSon
by: RedSon | last post by:
Chapter 2: How to handle Exceptions When you call a program, sometimes you get a message about an Unhandled exception type. This means, that something throws (or might throw) an Exception, but the compiler doesn't know, what to do then. You can deal with this in two different ways: Throw the Exception further (pass it on to some other...
0
6490
RedSon
by: RedSon | last post by:
Chapter 3: What are the most common Exceptions and what do they mean? As we saw in the last chapter, there isn't only the standard Exception, but you also get special exceptions like NullPointerException or ArrayIndexOutOfBoundsException. All of these extend the basic class Exception. In general, you can sort Exceptions into two groups:...
0
7801
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main...
1
7808
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8096
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5616
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3739
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3749
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1335
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1055
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.