手写源代码(二)——bind原理

bind与call、apply不同的是,bind返回的是一个新函数,改函数不会立即执行。
举个栗子,说明一下bind的功能。

  var x = 10;
        function show1(){
            console.log(this.x);
        }
        var obj1 = {
            x:20
        }
        var newShow = show1.bind(obj1);
        newShow();//x = 20

bind原理

// bind功能:
        // function A(){}
        // var  o = {},x = 1,y = 2,z = 3;
        // var B = A.bind(o,x,y,z);
        // B('c');
        // 1.函数A调用bind时,需要传递的参数o,x,y,z...,传递的第一个参数是this即将指向的对象
        // 2.返回新的函数B
        // 3.函数B在执行的时候,具体的功能实际上还是使用A,只不过this的指向变成了o,不传的时候this指向window
        // 4.函数B在执行的时候,传递的参数会拼接到x,y,z的后面,一并在内部传递给A执行
        // 5.当以new B()的时候,构造函数constructor依旧是A,而且o不会起到任何作用

        //要让所有函数都可以调用myBind,就要写在原型上
        Function.prototype.myBind = function (target) {
            //target改变返回函数执行的this指向
            var self = this;
            var args = [].slice.call(arguments, 1);
            var tmp = function () { };
            var f = function () {
                //如果是new出来的,则新函数的constructor还是旧函数,
                var arg = [].slice.call(arguments, 0);
                //执行的是A函数 self  this new tmp() this在原型链上能否找到原型
                return self.apply(this instanceof tmp ? this : (target || window), args.concat(arg));//根据参数改变this的指向
            }
            tmp.prototype = self.prototype;
            f.prototype = new tmp();
            return f;
        }
发布了10 篇原创文章 · 获赞 11 · 访问量 1707

猜你喜欢

转载自blog.csdn.net/qq_40619263/article/details/104399957