手写源码 -- bind,call,aplly

bind

  • bind用法fn.bind(thisobj,参数1,参数2,。。。)
            this.a = 1;
            var mode = {
                a: 10,
                getA: function (...rest) {
                    return rest.reduce((pre, value) => {
                        console.log(pre);
                        return (pre += value);
                    }, this.a);
                }
            };
            console.warn(mode.getA(1, 2, 3)); //16

            var mode2 = mode.getA; //其中的this指向指向window
            console.error(mode2(1, 2, 3)); //7

            var mode2 = mode.getA.bind(mode);//其中this指向mode
            console.error(mode2(1, 2, 3)); //16

js写bind函数

            Function.prototype.bindFn = function () {
                var _this = this;  //保存原函数
                var context = [].shift.call(arguments);  //保存第一个参数为上下文的this
                var args = [].slice.call(arguments);  //将剩余的参数整合成数组
                return function () {
                    return _this.apply(context, [].concat.call(args, [].slice.call(arguments)));
                };
            };

call和apply是改变this指向,只是参数不一样,call是可以传多个参数,apply是第二个参数是数组

call

            Function.prototype.callFn = function (content) {
                content = content || window;
                content.fn = this;
                var args = [...arguments].slice(1);
                var result = content.fn(...args);
                delete content.fn;
                return result;
            };

apply

            Function.prototype.applyFn = function (content, args) {
                if (!(args instanceof Array)) throw new Error('传入需要的是数组');
                content = content || window;
                content.fn = this;
                var result = content.fn(...arguments);
                delete content.fn;
                return result;
            };
posted @ 2021-03-30 18:39  ~~Distance  阅读(81)  评论(0)    收藏  举报