js source code analysis (3) - Bind

js source code (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>
</head>

<body>
    <script>
        function demo() {
      
      
            console.log(this);
            name = "2";
        }
        
        var obj = {
      
      
            name: '1',
            age: 2,
        }
        Function.prototype.myBind = function () {
      
      
            // 1. 存储改变this指向的对象
            var target = arguments[0] || window;
            var _arg = Array.from(arguments).slice(1);
            // 2. 找出最终要指向的函数 找到demo
            var self = this;
            return function () {
      
      
                // 执行demo 并且将demo的this指向 改为 target
                var arg = Array.from(arguments)
                target.fn = self;
                target.fn(...(_arg.concat(arg)));
            }
        }

        var fn = demo.myBind(obj);
        fn(1, 2, 3, 4, 5, 6)
    </script>
</body>

</html>

Guess you like

Origin blog.csdn.net/emm_10_01/article/details/122608733