bind 实现原理

<!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>
    <style>
        *{
            margin: 0;
            padding: 0;
        }

        html,body{
            height: 100%;
            overflow: hidden;
            background: -webkit-linear-gradient(top left,lightblue,lightpink);
        }
    </style>
</head>
<body>
    <script>
 
        let obj = {
             name:"Eric",
             age:29 
        }

        function fn(x,y,ev){
            console.log(this,x,y, x + y,ev);  
        }

        // document.body.onclick = fn.bind(obj,10,20)

        // document.body.onclick = function(ev){
        //     fn.call(obj,10,20,ev)
        // }

        // 原理: '闭包' 柯里化
        Function.prototype.bindOne = function(context,...params){

            // this ->fn 当前要执行的函数
            // context -> obj 需要改变的 this
            // params -> [10,20] 需要给函数 传递的实参信息 
            let that = this;
            return function proxy(...args){
                params = params.concat(args)
                return that.call(context,...params)
            } 
        }
 
        document.body.onclick = fn.bindOne(obj,50,20) 
   
    </script>
</body>
</html>
posted @ 2021-07-21 16:13  13522679763-任国强  阅读(121)  评论(0)    收藏  举报