html
html
1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
</body>
</html>
Enter to Rename, Shift+Enter to Preview
css
css
1
2
3
body {
}
Enter to Rename, Shift+Enter to Preview
js
js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
See question for more context on this code:
- https://www.sololearn.com/Discuss/669904/please-illustrate-javascript-closure-with-example
*/
//Global scope
var max_attempts_allowed = 5;
//Global Scope: Parent function with a nested function closure.
var do_something = (function(){
//Private Scope: attempts is like a private variable.
var attempts = 0; //Number of times something is done.
//Private Scope function available only to the closure.
var action_allowed = function(){
log("<li>Attempts: " + attempts + "</li>", false);
}
//Another private Scope function available only to the closure.
var action_restricted = function(){
log("<li>Max Attempts Exceeded (based on private variable: attempts value)</li>", false);
}
//This closure has access to the private scope of the do_something() function.
return function (){
//Comparing the private scope variable against the global scope variable.
if(attempts < max_attempts_allowed){
Enter to Rename, Shift+Enter to Preview
BROWSER
Console
Run