Self-executing Anonymous Functions in Javascript


In Javascript, functions are objects. Therefore you can define objects by using functions like the following.

1
2
3
4
5
6
7
8
function Person(name, age)
{
  this.name = name;
  this.age = age;
}
 
var Jack = new Person("Jack Baul", 21);
alert(Jack.name + "-" + Jack.age);
function Person(name, age)
{
  this.name = name;
  this.age = age;
}

var Jack = new Person("Jack Baul", 21);
alert(Jack.name + "-" + Jack.age);

The anonymous functions are the ones without names. Therefore, instead of writing

1
2
3
4
5
6
function test(abc)
{
  alert(abc);
}
 
test(123);
function test(abc)
{
  alert(abc);
}

test(123);

You can write the following by omitting the function name.

1
2
3
4
(function(abc)
{
  alert(abc);
})(123);
(function(abc)
{
  alert(abc);
})(123);

Therefore, it is not difficult to understand the scoping in the self-executing anoymous functions.

1
2
3
(function(){
  // temporary scope
})();
(function(){
  // temporary scope
})();

Example is given below.

1
2
3
4
5
6
7
8
var obj = new ActiveXObject("WScript.Shell");
 
(function (abc){
  var test = "Hello, " + abc;
  obj.popup(test);
})("World!");
 
obj.popup(test);  // test undefined
var obj = new ActiveXObject("WScript.Shell");

(function (abc){
  var test = "Hello, " + abc;
  obj.popup(test);
})("World!");

obj.popup(test);  // test undefined

The test variable only exists in the local function scope i.e. it uses var to declare that it is local otherwise will be treated as a global.

It is also worth to note that in Javascript, the order does not matter when it comes to function declaring. For example, the following will still work.

1
2
3
4
5
6
7
var obj = new ActiveXObject("WScript.Shell");
obj.popup(test("123"));
 
function test(abc)
{
  return abc + "test";
}
var obj = new ActiveXObject("WScript.Shell");
obj.popup(test("123"));

function test(abc)
{
  return abc + "test";
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
261 words
Last Post: Simple Profiling in Python
Next Post: Batch Programming Revisited, Chess Board Printing

The Permanent URL is: Self-executing Anonymous Functions in Javascript

Leave a Reply