Vue源码分析(函数拦截思想)

函数拦截

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        //在函数的原有基础上增加额外的操作:函数的拦截

        // 1.使用一个临时的函数名存储函数
        // 2.重新定义原来的函数
        // 3.定义扩展的功能
        // 4.调用临时的函数

        function func() {
            console.log('原始功能')
        }
        
        let _tempFn = func

        func = function () {
            _tempFn()
            console.log('新的扩展功能')
        }

        func();  //打印原始功能  //打印扩展功能

    </script>
</body>
</html>

数组拦截

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let ARRAY_METHOD = [
            'push',
            // 'pop',
            'shift',
            'unshif',
            'revers',
            'sort',
            'splice',
        ]

        //思路  原型式继承  修改原型链的结构
        let arr = []
        //继承关系: arr -> Array.prototype -> object.prototype -> ....
        //继承关系: arr -> 改写的方法 -> Array.prototype -> object.prototype -> ....
        
        let array_methods = Object.create( Array.prototype)

        ARRAY_METHOD.forEach( method => {
            array_methods[method] = function () {
                //调用原来的方法
                console.log('调用拦截')
                let res = Array.prototype[ method ].apply( this , arguments)
                return res
            }
        } )

        arr.__proto__ = array_methods

        //vue  源码中 进行判断
        //如果 浏览器支持__proto__ ok
        //如果不支持  vue 使用混入法

    </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值