forked from kshirish/Javascript-Garden
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclosures.js
68 lines (52 loc) · 1.13 KB
/
closures.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
function Counter(start) {
var count = start;
return {
increment: function() {
count++;
},
get: function() {
return count;
}
}
}
var foo = Counter(4);
foo.increment();
foo.get(); // 5
//closures within a loop
for(var i = 0; i < 10; i++) {
(function(e) {
setTimeout(function() {
console.log(e);
}, 1000);
})(i);
}
//an alternative way
for(var i = 0; i < 10; i++) {
setTimeout(console.log.bind(console, i), 1000);
}
// Contructors
function Foo(){
this.bar = 55; // no explicit return
}
new Foo(); // 'this' will be returned
function Foo(){
return 55; // explicit return of a non-object
}
new Foo(); // new object will be returned
function Foo(){
return {bar : 55} // explicit return of an object
}
new Foo(); // {bar: 55} will be returned
//factories
function Person() {
var obj = {};
obj.name = 'Gaurav';
var age = 21;
obj.setName = function(name) {
this.name = name;
}
obj.getAge = function() {
return age;
}
return obj;
}