Prerequisites for Using AngularJS
Interested in learning AngularJS? First you'll need to understand functions for encapsulation, using modules for functions, global variables, and more.
Join the DZone community and get the full member experience.
Join For FreeAngular JS is an open-source JavaScript framework from Google and can be downloaded from https://angularjs.org/.
Important concepts before start playing with AngularJS
Angular is based on the following concepts:
- Using function expression instead of the function declaration
- Functions for encapsulation
- Using modules for functions
- Avoid using global variables
Function Expressions vs. Function Declarations
Function declaration
- A variable declaration starts with var. A function declaration starts with function.
- The JS object created is the same as a function name. In following case an object with the name myFunction created.
- A function declaration is parsed and executed before any other expressions.
function myFunction(){console.log (“I am in myFunction”);}
Function expression
Assign a function to a variable.
By doing this, you can dynamically change the call to the function.
Use inside functions to create encapsulation and make your code more modular:
var myWork=function(){
console.log(“myWork Invoked”);
};
Function expressions are of two types:
1) Anonymous function expression:
var myWork=function(){
console.log(“myWork Invoked”);
};
2) Named function expression:
var myWork=function myWorkFunction(){
console.log(“myWork Invoked”);
};
Functions for Encapsulation
Function expressions are good for encapsulation.
Consider the following simple example:
//Step 1: – concentrate on implementation logic: -Function expression with global variable myProcess
var myProcess=function myProcessF(){
var preProcess=function(){
console.log(“in preProcess”);
};
var postProcess=function(){
console.log(“in postProcess”);
};
var doProcess=function(){
console.log(“in process”);
};
// Some private function which used internally
var somePrivateFunction=function(){
console.log(“some internal function”);
}
//Expose functions and variable which used outside this function: Good example of encapsulation
return{
//Aliasing
preProcessing:preProcess,
postProcessing:postProcess,
doProcessing:doProcess
};
};
//Invoke Function
var process =myProcess();
process.preProcessing();
process.doProcessing();
process.postProcessing();
When this code executed it gives the following output:
Avoid Creating Global Variables
By looking at above example, we can see that myProcess, process are global variables. These types of variables are available across the whole page (i.e. to each JS) hence they are susceptible to overriding. One needs to avoid creating global variables with the help of IIFY:
(function() {
// The code here executed once in its own scope
}());
Opinions expressed by DZone contributors are their own.
Comments