-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathitem_11.js
More file actions
70 lines (62 loc) · 2.05 KB
/
Copy pathitem_11.js
File metadata and controls
70 lines (62 loc) · 2.05 KB
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
69
70
// get comfortable with closures
// Notes: undersstanding closures requires learning three essential facts
// 1. JavaScript allows you to refer to variables that were defined outside of
// the current function.
//
// 2. Functions can refer to variables defined in outer functions even after
// those outer functions have returned.
// -- Note: functions are first class objects
//
// 3. Closures can update the values of outer variables since they store
// references to their outer variables, than copying their values
function makeSandwich() {
var magicIngredient = "peanut butter";
function make(filling) {
return magicIngredient + " and " + filling;
}
return make("jelly");
}
makeSandwich(); // "peanut butter and jelly
function sandwichMaker() {
var magicIngredient = "peanut butter";
function make(filling) {
return magicIngredient + " and " + filling;
}
return make;
}
var f = sandwichMaker();
f("jelly"); // "peanut butter and jelly"
// even though sandwichMaker already returned, 'make' remembers the value of
// magicIngredient
//
// JavaScript functions internallly store any variable they may refer to that
// are defined in their enclosing scopes.
//
// Functions that keep track of variables from their containing scopes are
// known as 'closures'
//using an anonymous function
function bestSandwichMaker(magicIngredient) {
return function(filling) {
return magicIngredient + " and " + filling;
};
}
var hamAnd = bestSandwichMaker("ham");
hamAnd("cheese"); // "ham and cheese"
hamAnd("mustard"); // "ham and mustard"
var turkeyAnd = bestSandwichMaker("turkey");
turkeyAnd("Swiss"); // "turkey and Swiss"
turkeyAnd("Provolone"); // "turkey and Provolone"
// fact #3
function box() {
var val = undefined;
return {
set: function(newVal) { val = newVal; },
get: function() { return val; },
type: function() { return typeof val; }
};
}
var b = box();
b.type(); // "undefined"
b.set(98.6);
b.get(); // 98.6
b.type(); // "number"