-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvariableScope.js
More file actions
171 lines (106 loc) · 2.43 KB
/
Copy pathvariableScope.js
File metadata and controls
171 lines (106 loc) · 2.43 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
/*
Variable Scope in Javascript
*/
/*
Javascript has two basic scopes for variables:
* Global and Function Scope
*/
//Example of a globally scope variable:
g = 'global variable!';
function setGlobalInAFunction() {
g_2 = 'global variable!'; //attached to the global scope
}
function callGlobal() {
console.log(g);
}
function callGlobalInFunction() {
console.log(g_2);
}
//callGlobal();
// setGlobalInAFunction();
// callGlobalInFunction();
/*
Problems with global references:
* Can be easily overwritten
* Takes Javascript runtime longer to find when using them
var:
* scoped to the function it is defined in
*/
/*
Hoisting: Declared variables will be available anywhere inside of the function they were declared in.
*/
function hoist() {
// if(true) {
// var h = 'hoisted variable name';
// }
// if (false) {
// h2 = 'hoisted!';
// }
// console.log(h2)
//Better way of doing the same thing:
var h,
h2;
if(true) {
h = 'hoisted variable name';
}
if(false) {
h2 = 'hoisted!';
}
console.log("h = " + h);
console.log("h2 = " + h2);
}
/*
*/
// hoist();
/*
undefined != 'not' defined
undefined --> exists but has no reference
*/
/*
A function defined without a function around it will be defined
in the global scope of the js runtime.
We can scope other functions inside functions.
If you have a function with a function inside it then the variables
declared in the outer function can be accesed from within the child
function; 'closure'.
*/
function outerScope() {
var f;
function getf() {
if(true) {
f = 'closured var!';
}
console.log(f);
}
getf();
console.log(f);
}
// outerScope();
/*
Immediate Functions / Javascript Modules
*/
//Local Access to global data
/*
var myModule = (function($,globalScope){
console.log($);
globalScope.something = 'something in the global scope';
})(jQuery, this);
*/
MyObject = (
function() {
var privateCount = 0;
var Obj = function() {
this.inc = function() {
privateCount += 1;
return privateCount;
}
};
return Obj;
}
)();
var counter1 = new MyObject();
var counter2 = new MyObject();
console.log(counter1.inc());
console.log(counter1.inc());
console.log(counter1.inc());
console.log(counter2.inc());