-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSinglePattern.html
41 lines (40 loc) · 1.17 KB
/
SinglePattern.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Single Pattern</title>
</head>
<body>
<button id="btn">点我登录</button>
<script>
class Login {
createLayout() {
console.log('invoked')
let theDiv = document.createElement('div');
theDiv.innerHTML = '我是浮窗'
document.body.appendChild(theDiv)
theDiv.style.display = 'none'
return theDiv
}
}
class Single {
getSingle(fn) {
let result;
return function () {
return result || (result = fn.apply(this, arguments))
}
}
}
let theBtn = document.getElementById('btn')
let single = new Single()
let login = new Login()
// 由于闭包, createLoginLayer 对 result 的引用, 所以当single.getSingle 函数执行完之后,内存中并不会销毁 result
// 之后点击按钮是,根据 createLoginLayer 函数的作用域链中已经存在result,所以直接返回result
let createLoginLayer = single.getSingle(login.createLayout)
theBtn.onclick= function() {
let layout = createLoginLayer()
layout.style.display = 'block'
}
</script>
</body>
</html>