面试官:手写一下call、apply、bind叭。

261 阅读1分钟

需要注意的点

  • call,apply使用Symbol()来防止重名
  • bind可以构建一个中间函数,防止实例修改原型上的属性
  • 不能使用箭头函数

call

   Function.prototype.myCall = function (ctx, ...args) {
            ctx = ctx || window;
            let fn = Symbol();
            ctx[fn] = this;
            let result = ctx[fn](...args);
            delete ctx[fn];
            return result;
        }

apply

Function.prototype.myApply = function (ctx, args) {
            ctx = ctx || window;
            let fn = Symbol();
            ctx[fn] = this;
            let result = args ? ctx[fn](...args) : ctx[fn]();
            delete ctx[fn];
            return result;
        }

bind

 Function.prototype.myBind = function (ctx, ...args) {
            let self = this;
            let fn = function () { };
            const bind = function () {
                let _this = this instanceof fn ? this : ctx;
                return self.apply(_this, [...args, ...arguments])
            }
            fn.prototype = this.prototype;
            bind.prototype = new fn();
            return bind;
        }

记录记录!