Self-executing Anonymous Functions in Javascript


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

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

function test(abc)
{
  alert(abc);
}

test(123);

You can write the following by omitting the function name.

(function(abc)
{
  alert(abc);
})(123);

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

(function(){
  // temporary scope
})();

Example is given below.

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.

var obj = new ActiveXObject("WScript.Shell");
obj.popup(test("123"));

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

–EOF (The Ultimate Computing & Technology Blog) —

244 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 (AMP Version)

Leave a Reply