Tag Archives: closures

Writing a jQuery plugin – (part 1). Good practices!

JavaScript flexibility

In JS you have the natural flexibility to extend an object you have previously declared. Even more you can extend any native objects! That makes the writing of a jQuery, or whatever javascript library, plugins to be very easy.

As you may know in JS you can have object declared like that:

var obj = { a : 1, b : 2 };

That is an object with two properties a and b which values are respectively 1 and 2. If you’d like to extend this object later you can just write:

obj.c = 3

and now the object looks like that:

{ a : 1, b : 2, c : 3 }

That’s perfect when you’d like to write plugins to jQuery. Continue reading Writing a jQuery plugin – (part 1). Good practices!

JavaScript closures in brief

What’s a closure

Well every javascript programer knows that a variable defined in javascript file with the var declaration is global into all javascript code.

var a = 12;
console.log(a);

that code prints 12 into the console.

Note: console object is visible in Firefox and Safari, but not in IE, and here’s used just for the test!

Here comes the closures

Let’s assume I’ve two javascript files.

file1.js:

var a = 12;

file2.js:

a = 13;

Than obviously if I print out the variable a in file2.js after that line, I’ll have the value of a equal to 13, and this will be the value of the variable a from the file1.js, because that’s obviously the same variable. Continue reading JavaScript closures in brief