每日4道面试题(JS)

1、手撸call()方法

 Function.prototype._call = function (ctx, ...args) {
        if(typeof this !== 'function') {
          new TypeError("this is not function")
        }

        ctx.fn = Symbol('fn');
        ctx.fn = this;

        let res = ctx.fn(...args);

        delete ctx.fn;

        return res;
}

2、手撸apply()方法

   Function.prototype._apply = function (ctx, ...args) {
        if(typeof this !== 'function') {
          new TypeError("this is not function")
        }

        ctx.fn = Symbol('fn');
        ctx.fn = this;

        let res = ctx.fn(...args);

        delete ctx.fn;

        return res;
  }

3、手撸bind()方法

 Function.prototype._bind = function (ctx, ...args) {
        if(typeof this !== 'function') {
          new TypeError("this.not typeError");
        }

        let self = this;

        return function F () {
          if(this instanceof F) {
            return new self(...args, ...arguments)
          }
          return self.apply(ctx, [...args, ...arguments])
        }
}

4、函数柯里化

// 实现一个add方法,使计算结果能够满足如下预期:
add(1)(2)(3) = 6;
add(1, 2, 3)(4) = 10;
add(1)(2)(3)(4)(5) = 15;
   function add() {
        const _args = [...arguments];
        function fn () {
          _args.push(...arguments);
          return fn;
        }

        fn.toString = function () {
            return _args.reduce((sum, cur) => sum + cur);
        }

        return fn;
      }
      add(1)(2)(3)                // 6
      add(1, 2, 3)(4)             // 10
      add(1)(2)(3)(4)(5)          // 15
      add(2, 6)(1)                // 9
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容