JavaScript closures
Closures are powerful features of JavaScript.
A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
Many developers were first introduced with closures when they try to execute code that similar to given below
for (var i = 0; i < aLinks.length; i++) {
    aLinks[i].onclick = function() {
        alert(i);
    }

}
Code contains an error that can be explained as follows.
It doesnt matter which link is clicked. We see only the last number(aLinks.length - 1).
We can fix an error. Lets create a closure function that creates a local copy of variable i.
for (var i = 0; i < aLinks.length; i++) {
   (function(i) {
      aLinks[i].onclick = function() {
         alert(i);
      }
   })(i);
}

Data encapsulation

In object oriented languages like Java we use private/protected and public methods in classes. Lets emulate OOP behavior in JavaScript class.
var o = new Helloer();
o.sayHello('Mike');

function Helloer() {
	// private scope
	var say = function(sMsg) {
		alert(sMsg);
	}

	// public scope
	return {
		sayHello : function(sName) {
			say('Hello ' + sName);
		}

	};

}

Links

May 20th, 2011
Back to main
Moi krug - Yernat Assanov
Advertisement
Documentolog
(C) 2010, kseeker
Email: kseeker@yandex.kz
Используются технологии uCoz