手写bind

bind里面的原理就是使用apply 或者使用call来改变this指针

Function.prototype.myBind = function (ctx = window) {
            let self = this;
            let args = [...arguments].slice(1);
            return function () {
                self.apply(ctx, args.concat(...arguments))
            }
        }

        function add() {
            console.log(this);
            console.log(arguments);
        }
        class Person {
            constructor() {
                this.name = '1231'
            }
        }
        add.myBind(new Person(), 1, 2)(3, 4)

  

  

posted @ 2020-11-09 11:08  王室  阅读(61)  评论(0编辑  收藏  举报