xinggevip

Es2015 Reflect.apply()拦截函数
index.html<!DOCTYPE html> <html lang="en&qu...
扫描右侧二维码阅读全文
20
2019/06

Es2015 Reflect.apply()拦截函数

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        function fn(){
            return '我是函数'
        };
        let newFn = new Proxy(fn,{
            apply(){
                return '不好意思,被我拦截了';
            }
        });
        console.log(newFn());   // 不好意思,被我拦截了

        console.log('============================');

        function sum(a,b){
            return a + b;
        };
        let newSum = new Proxy(sum,{
            apply(target, context, args){
                // console.log(target, context, args);
                // console.log(...arguments);  //和上面那句话打印一致

                // 反射
                return Reflect.apply(...arguments);
            }

        });
        console.log(newSum(2,3));   // 5
        
        console.log('==============================');

        // Reflect.apply()第一个参数时函数,第二个参数时this指向,第三个参数时传递的值
        let res = Reflect.apply(Math.ceil,null,[9.8]);
        console.log(res);   // 10

    
    </script>
</body>
</html>
Last modification:June 20th, 2019 at 10:15 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment