Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path063-function-constructor.js
More file actions
Latest commit
101 lines (73 loc) · 2 KB
/
Copy path063-function-constructor.js
File metadata and controls
101 lines (73 loc) · 2 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
// 1: FUNCTIONS ARE OBJECTS
functionname(params){
return`Hello, ${params}`
}
console.log(name.params)// name
console.log(name.length)// 1
name.callCount=0;
name.version="1.0"
console.log(name.version)// 1.0
// 2: THE FUNCTION CONSTRUCTOR
// Traditional way
functionadd(a,b){
returna+b;
}
// Using Function constructor
constaddConstructor=newFunction('a','b','return a + b');
console.log(add(5,3));// 8
console.log(addConstructor(5,3));// 8
constx=10;
functionnormal(){
returnx;// Works - accesses outer scope
}
constconstructed=newFunction('return x');
// Error! Only has global scope
// 3: BUILT-IN FUNCTION PROPERTIES
functioncalculateTotal(){
return100;
}
console.log(calculateTotal.name);// "calculateTotal"
constmultiply=(a,b)=>a*b;
console.log(multiply.name);// "multiply"
functionlogCall(fn, ...args){
console.log(`Calling: ${fn.name}`);
returnfn(...args);
}
functionadd(a,b){
returna+b;
}
console.log(add.length);// 2
functionwithRest(a,b, ...rest){}
console.log(withRest.length);// 2 (rest params don't count)
functionwithDefault(a,b=5){}
console.log(withDefault.length);// 1 (stops at first default)
functionPerson(name){
this.name=name;
}
Person.prototype.greet=function(){
return`Hi, I'm ${this.name}`;
};
constalice=newPerson("Alice");
console.log(alice.greet());// "Hi, I'm Alice"
// 4: CUSTOM PROPERTIES & PRACTICAL USE
// Function Counter:
functiontrackCalls(){
trackCalls.count++;
console.log(`Called ${trackCalls.count} times`);
}
trackCalls.count=0;
trackCalls();// Called 1 times
trackCalls();// Called 2 times
// Memoization (Caching):
functionfibonacci(n){
if(n<=1)returnn;
if(fibonacci.cache[n]){
returnfibonacci.cache[n];
}
constresult=fibonacci(n-1)+fibonacci(n-2);
fibonacci.cache[n]=result;
returnresult;
}
fibonacci.cache={};
console.log(fibonacci(10));// 55
console.log(fibonacci(10));// 55 (cached!)