Quantcast
Channel: JavaScript – iAdvise blog
Viewing all articles
Browse latest Browse all 14

5 Minute JavaScript #8 Framework Design

$
0
0

In the last blogpost we talked about closures and how they provide a great way to hide variables and functions from the outside world. We can combine our knowledge about namespaces and closures to create a simple framework.

In JavaScript, frameworks aren’t just for external libraries. It’s good and common practice to define a JavaScript framework for your own application. This framework handles: namespaces, conflicts, modules, etc.. This framework is used for giving structure to your application, making it accessible, extendable, structured and readable.

In previous posts we talked about namespaces. These objects are fine for grouping functionality, but they don’t allow you to have shared variables for a certain package. When you add a closure that returns the framework object, you have a scope in which you can define package-specific variables and functions.

var Framework = function () {
	var privateVar = 'private';
	var publicVar = 'public';
    // you can declare functions inside functions!
	var privateFun = function () {}
	return {
		publicVar: 'public',
		publicVar: publicVar,
		getPublicVar: function () { return publicVar; },
		publicFun: function () {}
	};
}();

Note that the Framework function is executed immediately, resulting in an object that is stored in the Framework variable. However, the function allows you to define scoped variables and functions that are not accessible from outside the function.

This template provides you with an easy and elegant way to encapsulate code while still being able to export functions and properties.



Viewing all articles
Browse latest Browse all 14

Latest Images

Trending Articles





Latest Images