-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path063-function-constructor.js
More file actions
101 lines (73 loc) · 2 KB
/
063-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
function name(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
function add(a, b) {
return a + b;
}
// Using Function constructor
const addConstructor = new Function('a', 'b', 'return a + b');
console.log(add(5, 3)); // 8
console.log(addConstructor(5, 3)); // 8
const x = 10;
function normal() {
return x; // Works - accesses outer scope
}
const constructed = new Function('return x');
// Error! Only has global scope
// 3: BUILT-IN FUNCTION PROPERTIES
function calculateTotal() {
return 100;
}
console.log(calculateTotal.name); // "calculateTotal"
const multiply = (a, b) => a * b;
console.log(multiply.name); // "multiply"
function logCall(fn, ...args) {
console.log(`Calling: ${fn.name}`);
return fn(...args);
}
function add(a, b) {
return a + b;
}
console.log(add.length); // 2
function withRest(a, b, ...rest) {}
console.log(withRest.length); // 2 (rest params don't count)
function withDefault(a, b = 5) {}
console.log(withDefault.length); // 1 (stops at first default)
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hi, I'm ${this.name}`;
};
const alice = new Person("Alice");
console.log(alice.greet()); // "Hi, I'm Alice"
// 4: CUSTOM PROPERTIES & PRACTICAL USE
// Function Counter:
function trackCalls() {
trackCalls.count++;
console.log(`Called ${trackCalls.count} times`);
}
trackCalls.count = 0;
trackCalls(); // Called 1 times
trackCalls(); // Called 2 times
// Memoization (Caching):
function fibonacci(n) {
if (n <= 1) return n;
if (fibonacci.cache[n]) {
return fibonacci.cache[n];
}
const result = fibonacci(n - 1) + fibonacci(n - 2);
fibonacci.cache[n] = result;
return result;
}
fibonacci.cache = {};
console.log(fibonacci(10)); // 55
console.log(fibonacci(10)); // 55 (cached!)