实现call,apply,bind,new。

2018-01-22  本文已影响0人  pawN_f294
    Function.prototype._call = function (context) {
      // 传入的this值为null或者为空的时候
      var context = context || window;

      var args = [];
      for (var i = 1; i < arguments.length; i++) {
        args.push('arguments[' + i + "]");
      }

      context.fn = this;

      var res = eval('context.fn('+ args +')');

      delete context.fn;
      return res;
    }
  • 要实现call的功能主要在于把函数的this指向我们想要的对象上
    把函数赋值给要指向的对象的一个属性,然后再调用就该属性。
  • 接着用eval的方式调用该函数,以达到参数的正确传递。
    类似于 context.fn(argument[0],argument[1],argument[2]...)
    Function.prototype._apply = function (context, arr) {
      // 传入的this值为null或者为空的时候
      var context = context || window;
      context.fn = this;
      var res;

      if (!arr) {
        res = context.fn();
      }
      else {
        var args = [];
        for (var i = 0; i < arr.length; i++) {
          (function (i) {
            args.push('arr[' + i + ']');
          })(i)
        }
        var res = eval('context.fn('+ args +')');
    }
  Function.prototype._bind = function (context) {
    if (typeof this !== "function") {
      throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
    }
    var that = this;
    var args = Array.prototype.slice.call(arguments, 1);

    var fn = function () {
      args.concat(Array.prototype.slice.call(arguments));
      return that.apply(this instanceof fn ? this : context, args);
    }

    fn.prototype = Object.create(this.prototype);
    return fn;
  }

bind的实现在于利用闭包保留要 调用函数 和 要指向上下文对象的引用,下次调用时再执行该函数。要注意两个点。

  • 一个是参数的合并,在调用bind函数时传入的后续参数会和执行该函数时传入的参数合并起来。
  • 二是用new调用该函数时的情况,在用new调用该函数时函数里面的this指向会指向到new出来的新对象上,所以在调用的时候要判断一个是否是new调用的。
    function _new () 
      var args = Array.prototype.slice.call(arguments);
      var fn = args.shift();

      var context = Object.create(fn.prototype);

      var res = fn.apply(context, args);
      return (typeof res === object && res !== null) ? res : context;
    }
    // 用法 第一个参数为构造函数,之后的为参数。
    _new(Otaku, ...)

new的功能主要是返回一个新的对象,把对象指向函数的this值,然后把对象__proto__属性指向函数的prototype属性
要注意的是如果构造函数返回的是一个对象,就直接放回该对,否则返回我们想要的新对象。

上一篇 下一篇

猜你喜欢

热点阅读