-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIIFEs.js
64 lines (47 loc) · 1.25 KB
/
IIFEs.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
/**
* An Introduction to IIFEs - Immediately Invoked Function Expressions
*/
(function () {
// logic here
console.log("Hello World");
})();
// Named function declaration
function myFunction() {
/* logic here */
}
// Assignment of a function expression to a variable
var myFunction = function () {
/* logic here */
};
// Assignment of a function expression to a property
var myObj = {
myFunction: function () {
/* logic here */
}
};
// Anything within the parentheses is part of an expression
(function () {
/* logic here */
});
// Anything after the not operator is part of an expression
!function () {
/* logic here */
};
(function () {
var foo = "bar"; // local variable
console.log(foo); // bar
})();
// console.log(foo); // ReferenceError: foo is not defined
// you could explicitly name and then invoke a function to achieve the same ends.
function myImmediateFunction() {
var foo = "bar";
console.log(foo); // Outputs: "bar"
}
myImmediateFunction();
// console.log(foo); // ReferenceError: foo is not defined
// It is worth pointing out that you can easily pass arguments into the IIFE as well.
var name = "foo";
(function (innerFoo) {
// Outputs: "foo"
console.log(innerFoo);
})(name);