html
html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
<title>JS Closure Demo</title>
</head>
<body>
<div>
<input type="number" id="Input" value="0" />
<button type="button" id="Submit">Add</button>
</div>
<div>Results:
<div>No closure: <span id="Result1"></span></div>
<div>Closure 1: <span id="Result2"></span></div>
<div>Closure 2 (object): <span id="Result3"></span></div>
</div>
</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
// no closure
function addSomeNoClosure(num) {
var add = 10;
return add + num;
}
// closure
function addSomeClosure(num) {
var add = 10;
return _closure();
function _closure(){
return add + num;
}
}
// object with closure
var addObj ={};
(function (){
var add = 10;
addObj.addSome = function (num){
return add + num;
}
})();
window.onload = function() {
var btn = document.getElementById("Submit"),
Enter to Rename, Shift+Enter to Preview
BROWSER
Console
Run