473,383 Members | 1,815 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,383 developers and data experts.

An Introduction to Function Objects

pbmods
5,821 Expert 4TB
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 myAwesomeFunction.

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 myAwesomeFunction 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 myAwesomeFunction.

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.onreadystatechange 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.onreadystatechange 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 9225
acoder
16,027 Expert Mod 8TB
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 Expert 100+
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 Expert 4TB
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
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...
13
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...
12
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
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...
12
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...
5
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
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...
0
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...
0
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.