Skip to content Skip to navigation

Connexions

You are here: Home » Content » Anonymous functions

Navigation

Recently Viewed

This feature requires Javascript to be enabled.
 

Anonymous functions

Module by: Hannes Hirzel. E-mail the author

Summary: In JavaScript anonymous functions are often used. The module introduces the idea and gives examples.

Introduction

NOTE

THIS MODULE IS STILL A DRAFT.

In JavaScript functions may be defined as in other languages like C and PhP.

 function square(x) = {return x * x}

However in addition in JavaScript functions are objects. They may be defined as anonymous functions.

Definition

Wikipedia: In programming language theory, an anonymous function is a function (or a subroutine) defined, and possibly called, without being bound to an identifier.

This means that the function expression does not need an identifier or name. In JavaScript an object is created with the function expression.

Form

An anonymous function looks like this: function() { // statements } or function(x) { // statements }

An example of an anonymous function expression function(x) {return x * x} . Compare this to above where we had given square as the function identifier.

Assigning the function expression to a variable

The anonymous function expression may be assigned to a variable. var square = function (x) { return x * x}

Test

square(8) gives back 64. The function object may be referenced by another variable var sq = square; . Note that there are no invocation () brackets. sq(9) gives back 81.

Method definition with an anonymous function

A method is a property whose value is a function.

var myObj = {};
myObj.lengthOfSide = 9;
myObj.area = function() {return this.lengthOfSide * this.lengthOfSide};

With var myObj = {} a new object is created. With myObj.lengthOfSide = 9; a data property is assigned to it. And with myObj.area = function() {return this.lengthOfSide * this.lengthOfSide}; a method is assigned.

console.log(myObj.area()) puts 81 to the log.

console.log(myObj.area) gives back the function object(function () {return this.lengthOfSide * this.lengthOfSide;}).

Application examples

Using an anonymous function as an event handler

In the following example we get access to a button element by its name mySaveButton. This element has an onclick property. We use an anonymous function to assign an action which will be executed when the user clicks the button.



var button = document.getElementById("mySaveButton");
button.onclick = function() {monthTable.save()};

The action defined here is to call the save() method of an object called monthTable.

We want to add a button to the template of the HTML5 module.



var myButton = document.getElementById("myButton");

// assign an anonymous function to the onclick handler of the button

myButton.onclick = function() {
	var list = document.getElementById("beverages");
	var listlength = list.children.length;
	var note = document.getElementById("note");
	note.textContent = listlength + " types of beverages";
	}

list, listlength and note are all local variables in the anonymous function. Thus they do not contribute to a "pollution" of the global name space. This is a criticism people have on JavaScript that there might be a proliferation of global variables making JavaScript programs difficult to maintain (David Crockford, 2002). However if you declare them locally to functions this does not apply.

To make the example work we have to add HTML code for the button

< type="button" id="myButton" value="count" />
Here is the complete HTML page. "View source" shows the code.

XMLHttpRequest

When using an XHMLHttpRequest in AJAX applications an anonymous function may be used to define what to do when the requested data arrives:


var objXHR = new XMLHttpRequest();  
objXHR.open("GET", "http://www.mozilla.org/", true);  
objXHR.onreadystatechange = function (oEvent) {  
  if (objXHR.readyState === 4) {  
    if (objXHR.status === 200) {  
      console.log(objXHR.responseText)  
    } else {  
      console.log("Error", objXHR.statusText);  
    }  
  }  
};  
objXHR.send(null);  
Source: MDN Using XMLHttpRequest

window.onload

The window.onload event is fired when the document with all images has finished loading. Then some JavaScript code may be executed. This can be done with an anonymous function.

window.onload = function() {

   // execute JavaScript code her which works on the DOM

}
(Ref)

Further reading

Immediately-Invoked Function Expression (IIFE)

An anonymous function may be invoked immediately after being defined.

Note by John Resig

John Resig suggests to beginning JavaScript programmers to use var getData = function() { }; instead of function getData() { }.

JavaScript Garden

Function declarations and expressions

David Flanagan

JavaScript, The Definitive Guide, 6th edition, 2011; chapter 8.4 Functions as values

Wikipedia

Uses and examples in other languages.

Content actions

Download module as:

PDF | EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Add module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks