1. 沙箱模式
* 利用了 函数outer "间接" 的返回了一个或多个函数(obj里含有getA、setA、getB、setB函数)
* 外部函数outer 返回了 一个对象, 这个对象内书写多个函数
<script>
function outer() {
let a = 0
let b = 999
const obj = {
getA: function () {
return a
},
setA: function (val) {
a = val
},
getB() {
return b
},
setB(val) {
b = val
}
}
return obj
}
const res = outer()
let winA = res.getA()
res.setA(winA + 1)
console.log(res.getA())
</script>
案例1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="add1">+</button>
<input type="text" class="inp1" value="1">
<button class="sub1">-</button>
<script>
// 0. 获取标签
const add1 = document.querySelector('.add1')
const inp1 = document.querySelector('.inp1')
const sub1 = document.querySelector('.sub1')
// 通过沙箱模式创建变量
function outter() {
let count = 1
return {
getCount() {
return count
},
setCount(val) {
count = val
}
}
}
const res = outter()
add1.onclick = function () {
// 增加
let num = res.getCount()
res.setCount(num + 1)
inp1.value = res.getCount()
}
sub1.onclick = function () {
// 减少
let num = res.getCount()
res.setCount(num - 1)
inp1.value = res.getCount()
}
// 正常版写法
// let count = 1
// add1.onclick = function () {
// // 增加
// count++
// inp1.value = count
// }
// sub1.onclick = function () {
// // 减少
// count--
// inp1.value = count
// }
</script>
</body>
</html>
2. 沙箱模式语法糖
语法糖: 在不影响功能的情况下, 给我们提供了一些更简单的操作方式
function outter() {
let a = 1
return {
get a() {
return a
},
set a(val) {
a = val
}
}
}
const res = outter()
console.log(res.a)
res.a = 999
console.log(res.a)
3. 函数的柯里化
需求: 使用正则完成一个文本匹配
1. 普通版
const reg = /^\w{6,12}$/
const str = '12345'
console.log(reg.test(str))
2. 普通优化版
function testStr(fnReg, fnStr) {
const reg = fnReg
const str = fnStr
console.log(reg.test(str))
}
testStr(/^\w{6,8}$/, 'qwer')
3. 柯里化函数版:
一个函数接收多个参数能够完成功能, 柯里化函数就是将这一个函数拆分为两个函数
每个函数都只接受一个参数, 然后完成的功能相同
function fn(fnReg) {
return function (fnStr) {
return fnReg.test(fnStr)
}
}
const testNum = fn(/^\d{5,8}$/)
console.log(testNum('1234'))
const testName = fn(/^\w{6,12}$/)
console.log(testName('qwertyui'))