Repository navigation
Expand file tree
/
Copy pathmodule_weakmap_2.html
More file actions
48 lines (44 loc) · 1.56 KB
/
Copy pathmodule_weakmap_2.html
File metadata and controls
48 lines (44 loc) · 1.56 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive HTML Example - WeakMap</title>
</head>
<body>
<h1>Interactive HTML Example - WeakMap</h1>
<input id="input-bar" type="text" placeholder="Enter a value">
<button id="call-public-function">Call Public Function</button>
<script>
const myPrivateVar = new WeakMap();
const myPrivateMethod = new WeakMap();
class MyNamespace {
constructor() {
// A private counter variable
myPrivateVar.set(this, 0);
// A private function that logs any arguments
myPrivateMethod.set(this, foo => console.log(foo));
// A public variable
this.myPublicVar = 'foo';
}
// A public function utilizing privates
myPublicFunction(bar) {
let privateVar = myPrivateVar.get(this);
const privateMethod = myPrivateMethod.get(this);
// Increment our private counter
privateVar++;
myPrivateVar.set(this, privateVar);
// Call our private method using bar
privateMethod(bar);
}
}
const myNamespaceInstance = new MyNamespace();
// UI elements
const inputBar = document.getElementById('input-bar');
const callPublicFunctionButton = document.getElementById('call-public-function');
callPublicFunctionButton.addEventListener('click', () => {
myNamespaceInstance.myPublicFunction(inputBar.value);
});
</script>
</body>
</html>