Jansiel Notes

闭包,沙箱,防抖节流,函数柯里化,数据劫持......

函数创建与定义的过程

  • 函数定义阶段
    • 在堆内存中开辟一段空间
    • 把函数体内的代码一模一样的存储在这段空间内
    • 把空间赋值给栈内存的变量中
  • 函数调用阶段
    • 按照变量名内的存储地址找到堆内存中对应的存储空间
    • 在调用栈中开辟一个新的函数执行空间
    • 在执行空间中进行形参赋值
    • 在执行空间中进行预解析
    • 在执行空间中完整执行一遍函数内的代码
    • 销毁在调用栈创建的执行空间

不会销毁的函数执行空间

  1. 当函数内返回一个引用数据类型
  2. 并且函数外部有变量接收这个引用数据类型
  3. 函数执行完毕的执行空间不会销毁
  4. 如果后续不需要这个空间了,只要让变量指向别的位置即可
 1function fn() {
 2    const obj = {
 3        a: 1,
 4        b: 2
 5    }
 6    return obj
 7}
 8
 9const res = fn()
10console.log(res)
11
12// 如果后续不需要这个空间了, 只需要让 res 指向别的位置即可
13res = 100
14

闭包

  • 需要一个不会被销毁的执行空间
  • 需要直接或间接返回一个函数
  • 内部函数使用外部函数的私有变量
  • 概念 : 函数里的函数
  • 优点:
    • 可以在函数外访问函数内的变量
    • 延长了变量的生命周期
  • 缺点:
    • 闭包函数不会销毁空间,大量使用会造成内存溢出
 1function outer () {
 2    let a = 100
 3    let b = 200
 4
 5    // 我们说 inner 是 outer 的闭包函数
 6    function inner () {
 7        /**
 8         * 我使用了一个 a 变量, 但是 inner 自己没有
 9         * 所以我用的是 外部函数 outer 内部的变量 a
10        */
11        // console.log(a)
12        return a
13    }
14    return inner
15}
16
17// 我们说 res 是 outer 的闭包函数
18let res = outer()
19
20let outerA = res()
21console.log(outerA)
22

沙箱模式

  • 利用了函数内间接返回了一个函数
  • 外部函数返回一个对象,对象内书写多个函数
 1function outer () {
 2    let a = 100
 3    let b = 200
 4
 5    // 创建一个 沙箱, "间接的返回一个函数"
 6    const obj = {
 7        getA: function () {
 8            return a
 9        },
10        getB: function () {
11            return b
12        },
13        setA: function (val) {
14            a = val
15        }
16    }
17    return obj
18}
19
20// 得到一个沙箱
21const res1 = outer()
22
23console.log(res1.getA())    // 100
24console.log(res1.getB())    // 200
25
26res1.setA(999)
27console.log(res1.getA())    // 999
28
29// 重新得到一个沙箱
30const res2 = outer()
31console.log(res2.getA())    // 100
32

沙箱小案例

1<button class="sub">-</button>
2<input class="inp" type="text" value="1">
3<button class="add">+</button>
4<br>
5<button class="sub1">-</button>
6<input class="inp1" type="text" value="1">
7<button class="add1">+</button>
8
 1// 准备一个沙箱
 2function outer() {
 3    let a = 1
 4    return {
 5        getA() {
 6            return a
 7        },
 8        setA(val) {
 9            a = val
10        }
11    }
12}
13
14// 0. 获取元素
15const subBtn = document.querySelector('.sub')
16const addBtn = document.querySelector('.add')
17const inp = document.querySelector('.inp')
18
19// 0. 准备变量
20// let count = 1
21let res = outer()
22subBtn.onclick = function () {
23    let count = res.getA()
24    res.setA(count - 1)
25    inp.value = res.getA()
26}
27addBtn.onclick = function () {
28    // count++
29    let count = res.getA()
30    res.setA(count + 1)
31    inp.value = res.getA()
32}
33
34// 0. 获取元素
35const subBtn1 = document.querySelector('.sub1')
36const addBtn1 = document.querySelector('.add1')
37const inp1 = document.querySelector('.inp1')
38
39// 0. 准备变量
40let res1 = outer()
41subBtn1.onclick = function () {
42    let count = res1.getA()
43    res1.setA(count - 1)
44    inp1.value = res1.getA()
45}
46addBtn1.onclick = function () {
47    let count = res1.getA()
48    res1.setA(count + 1)
49    inp1.value = res1.getA()
50}
51

沙箱语法糖

  • 尽可能的简化沙箱模式的语法
  • 利用 get 和 set 进行操作数据
  • 语法糖:
    • 在不影响功能的情况下提供一点更适合操作的语法
 1function outer() {
 2    let a = 100
 3    let b = 200
 4
 5    return {
 6        get a() { return a },
 7        get b() { return b },
 8        set a(val) { a = val }
 9    }
10}
11
12let res = outer()
13console.log(res.a)
14console.log(res.b)
15res.a = 999
16console.log(res.a)   // 999
17

闭包面试题!!!!

 1function fun(n, o) {
 2    console.log(o)
 3
 4    const obj = {
 5        fun: function (m) {
 6            return fun(m, n)
 7        }
 8    }
 9
10    return obj
11}
12
13var a = fun(0)    // undefined
14a.fun(1)    // 0
15a.fun(2)    // 0
16a.fun(3)    // 0
17
18/**
19 *  var a = fun(0)
20 *  a.fun(1)
21 *  a.fun(2)
22 *  a.fun(3)
23 *
24 *  1. var a = fun(0)
25 *          调用 fun(QF001) 函数(QF001) 传递一个 参数 0
26 *              全局函数 fun (QF001) 的 形参 n == 0     形参 o == undefined
27 *          调用 fun 函数后, 会返回一个对象 存储在 变量 a 中, 这个对象内部有一个属性叫做 fun, 属性值为 一个函数(QF002),
28 *              所以我们可以通过 a.fun()   去调用这个函数
29 *
30 *  2. a.fun(1)
31 *      2.1 调用这个函数 会 return 一个函数 fun (为全局函数 QF001) 的调用结果,
32 *      2.2 调用全局函数 fun(m, n)       m 此时 传递的是 1, n 传递的是 0
33 *      2.3 执行全局函数 fun(m, n) 内部会输出第二个形参
34 *
35 *  3. a.fun(2)
36 *      2.1 调用这个函数 会 return 一个函数 fun(为全局函数 QF001) 的调用结果
37 *      2.2 调用全局函数 fun(m, n)  m 此时传递的是 2, n 传递的是 0
38 *      2.3 执行全局函数 fun(m, n) 内部会输出第二个形参
39 *
40*/
41

防抖与节流

防抖

  • 解释:在短时间内触发一件事,每次都用上一次的时间替代,也就是只执行最后一次
1        box.oninput = ((timerID) => {
2            return function (e) {
3                clearInterval(timerID)
4                timerID = setTimeout(() => {
5                    console.log('搜索了: ', e.target.value)
6                }, 300)
7            }
8        })(0)
9

节流

  • 解释:短时间内快速触发一件事,当一个事件处理函数开始执行的时候,不允许重复执行(瀑布流)
 1        box.oninput = ((flag) => {
 2            return function (e) {
 3                if (!flag) return
 4                flag = false
 5                setTimeout(() => {
 6                    console.log('搜索了: ', e.target.value)
 7                    flag = true
 8                }, 300)
 9            }
10        })(true)
11

柯里化函数

  • 定义:本质上还是一个函数,只不过将原本接收多个参数才能正常执行的函数拆分成多个只接收一个的函数
 1// 原本函数
 2        function reg (reg, str) {
 3            return reg.test(str)
 4        }
 5        // 柯里化后
 6        function reg(reg) {
 7            return (str) => {
 8                return reg.test(str)
 9            }
10        }
11        const res = reg(/^\w{3,5}$/)
12        console.log(res('123asd'));   // false
13        console.log(res('123'));      // true
14

封装柯里化函数案例

 1        /**
 2         *  函数柯里化封装
 3         *
 4         *  fn 函数能够帮助我们拼接一个 完整的网络地址
 5         *      a --- 传输协议: http      https
 6         *      b --- 域名:   localhost   127.0.0.1
 7         *      c --- 端口号: 0-65535
 8         *      d --- 地址:   /index.html     /a/b/c/index.html
 9         *
10         *
11         *  现在只有我们正确的传递了参数的数量才能够实现最好的拼接, 如果传递的参数数量不够也会运行函数, 但是字符串不太对
12         *
13         *  需求:
14         *      将当前函数处理成柯里化函数, 只有传递的参数数量足够的时候, 在执行函数内容
15        */
16        // 功能函数
17        function fn(a, b, c, d) {
18            return a + '://' + b + ':' + c + d
19        }
20        // 通过柯里化解决
21        function keli (callBack, ...args) {
22            return function (..._args) {
23                _args = [...args, ..._args]
24                if (_args.length >= callBack.length) {
25                    return callBack(..._args)
26                } else {
27                    return keli(callBack, ..._args)
28                }
29            }
30         }
31

数据劫持(代理)

将来在框架中我们通常都是 数据驱动视图 也就是说: 修改完毕数据, 视图自动更新

  • 数据劫持:以原始数据为基础,对数据进行一份复制
  • 复制出来的数据是不允许被修改的,值是从原始数据里面获取的
  • 语法: Object.defineproperty(哪一个对象,属性名,{配置项})
  • 配置项:
    • value:该属性对应值
    • writable:该属性确定是否允许被重写,默认值是false
    • emunerable:该属性是否可被枚举(遍历), 默认是 false
    • get:是一个函数,叫做getter获取器,可以用来决定改属性的属性值
      • get属性的返回值就是当前属性的属性值
    • set:是一个函数,叫做setter设置器,当修改属性值的时候会触发函数
    • set和get不能和其他三个属性一起用
1    <h1>姓名: <span class="name">默认值</span> </h1>
2    <h1>年龄: <span class="age">默认值</span> </h1>
3    <h1>性别: <span class="sex">默认值</span> </h1>
4    请输入年龄:<input type="text" name="" id="name">
5    <br>
6    请输入年龄:<input type="text" name="" id="age">
7    <br>
8    请输入性别:<input type="text" name="" id="sex">
9
 1        const nameEl = document.querySelector('.name')
 2        const ageEl = document.querySelector('.age')
 3        const sexEl = document.querySelector('.sex')
 4        const inp1 = document.querySelector('#name')
 5        const inp2 = document.querySelector('#age')
 6        const inp3 = document.querySelector('#sex')
 7        const obj = {
 8            name:'张三',
 9            age:18,
10            sex:'男'
11        }
12        function bindHtml(res) {
13            nameEl.innerHTML = res.name
14            ageEl.innerHTML = res.age
15            sexEl.innerHTML = res.sex
16        }
17        const app =  observer(obj, bindHtml)
18
19        inp1.oninput = function () {
20            app.name = this.value
21        }
22        inp2.oninput = function () {
23            app.age = this.value
24        }
25        inp3.oninput = function () {
26            app.sex = this.value
27        }
28
29    function observer (origin, callBack) {
30    const target = {}
31    // 数据劫持
32    for (let key in origin) {
33        Object.defineProperty(target, key, {
34            get () {
35                return origin[key]
36            },
37            set (val) {
38                origin[key] = val
39                callBack(target)
40            }
41        })
42    }
43    // 首次调用
44    callBack(target)
45    return target
46}
47

数据劫持 + 渲染 (vue功能实现)

 1<div id="app">
 2        <p>姓名:{{name}}</p>
 3        <p>年龄:{{age}}</p>
 4        <p>性别:{{sex}}</p>
 5        <p>用户:{{id}}</p>
 6    </div>
 7
 8    用户id:<input type="text" name="" id="">
 9
10    <script src="js/vue.js"></script>
11
12    <script>
13        const app = createApp({
14            el:'#app',
15            data:{
16                name:'张三',
17                age:20,
18                sex:'男',
19                id:'0001'
20            }
21        })
22        const inp = document.querySelector('input')
23        inp.oninput = function () {
24            app.id = this.value
25        }
26
27    </script>
28
 1function createApp(options) {
 2    // 安全判断(传参判断)
 3    // 1.1 el
 4    if (options.el === undefined) {
 5        throw new Error('el选项必须传递')
 6    }
 7    // 1.2 data
 8    if (Object.prototype.toString.call(options.data) !== '[object Object]') {
 9        throw new Error('data 属性必须是个对象')
10    }
11    // 1.3 el 不能为空
12    const root = document.querySelector(options.el)
13    if (root === null) throw new Error('el 必须传入,且root为有效元素')
14    // 2 数据劫持
15    const target = {}
16    for (let key in options.data) {
17        Object.defineProperty(target, key, {
18            get() {
19                return options.data[key]
20            },
21            set(val) {
22                options.data[key] = val
23                // 每次修改数据调用渲染函数
24                bindHtml(root, target, rootStr)
25            }
26        })
27    }
28    // 拿到根元素下面的结构(字符串形式)
29    const rootStr = root.innerHTML
30    // 首次调用
31    bindHtml(root, target, rootStr)
32    return target
33}
34function bindHtml(root, _data, _str) {
35    // 定义一个正则拿到{{......}}
36    const reg = /{{ *(\w+) *}}/g
37    const arr = _str.match(reg)
38    arr.forEach(item => {
39        const key = /{{ *(\w+) *}}/.exec(item)[1]
40        _str = _str.replace(item, _data[key])
41    });
42    root.innerHTML = _str
43}
44

数据劫持升级

自己劫持自己

  • 语法: Object.defineProperties(想要劫持得对象,配置项)
 1        const obj = {
 2            username:'admin',
 3            password:'123456',
 4            id:'0001'
 5        }
 6        for (let key in obj) {
 7            Object.defineProperties(obj, {
 8                // 对象里面默认把key当作字符串,通过[]语法实现将其当作变量
 9                ['_' + key]:{
10                    value:obj[key],
11                    writable:true
12                },
13                [key]:{
14                    get () {
15                        // 如果returnobj[key],每次return都会访问,
16                        // 然后触发get方法会形成死循环
17                        return obj['_' + key]
18                    },
19                    set (val) {
20                        obj['_' + key] = val
21                    }
22                }
23            })
24        }
25

数据代理(ES6)

  • 通过内置构造函数代理
  • 语法: new Proxy(想要代理得对象,)
  • 数据代理完成后,在向对象中添加属性,也可以自动完成代理
 1        const obj = {
 2            name:'zhangsan',
 3            age:18
 4        }
 5        const res = new Proxy(obj, {
 6            get (target, property) {
 7                return target[property]
 8            },
 9            set (target, property, val) {
10                target[property] = val
11            }
12        })
13        res.age = 20
14        console.log(res.age);
15        console.log(res.name);
16        // 数据代理后添加的数据也可以被代理
17        res.abc = 123
18        console.log(res);
19