Showing posts with label JavaScript. Show all posts
JavaScript Part-12 Closures
A closure in JavaScript is an inner function that has access to its outer function's scope, even after the outer function has returned control. A closure makes the variables of the inner function private. A
Simple example of a closure is shown below:
var count = (function () {
var _counter = 0;
return function () {return _counter += 1;}
})();
count();
count();
count();
// the counter is now 3
The variable count is assigned an outer function. The outer function runs only once, which sets the counter to zero and returns an inner function. The _counter variable can be accessed only by the inner function, which makes it behave like a private variable.
return function () {return _counter += 1;}
})();
count();
count();
count();
// the counter is now 3
The variable count is assigned an outer function. The outer function runs only once, which sets the counter to zero and returns an inner function. The _counter variable can be accessed only by the inner function, which makes it behave like a private variable.
JavaScript Part-11 IIFE ( Immediately invoked function expressions )
IIFE ( Immediately invoked function expression ) is a function that's executed as soon as it's created. It is a self invoking anonymous function. It has no connection with any events or asynchronous execution.
Explanation:
1. ( function( ) {
Syntax:
( function( ) {
// Code goes here
// ...
} )( );
1. ( function( ) {
// Code goes here
// ...
} )( );
All the code inside the function will be converted into an expression.
2. ( function( ) {
// Code goes here
// ...
} )( );
The second pair of parentheses calls the function resulting from the expression.
JavaScript Part-10 Event handlers
Event handlers are used to execute a function based on the action performed by the user like onclick, onload, onmouseover etc
In the below example 3 buttons are available on the web page - Touch me 1, Touch me 2 and Touch me 3
onClick event is fired when user clicks on each button.
Alert boxes are displayed on user button click.
Touch me 1 - Alert button code is written in html tag.
Touch me 2 - Function named "first" is called on onClick.
Touch me 3 - Function named "second" is called by passing a parameter named "a".
Example code for onClick event handler
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function first()
{
alert('Without parameter');
}
function second(a)
{
alert('With parameter '+a);
}
</script>
</head>
<body>
<form>
<!--alert box code in click event-->
<input type="button" value="Touch me 1" onClick="alert('Hello')" />
<!--Function called in click event-->
<input type="button" value="Touch me 2" onClick="first()" />
<!--Function with parameter called in click event-->
<input type="button" value="Touch me 3" onClick="second('Hello')" />
</form>
</body>
</html>
Output


