实现call,apply,bind,new。

  • 模仿call的实现
    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]...)
  • apply的实现 (实现类似call)
    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 +')');
    }
  • bind的实现
  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调用的。
  • 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属性
要注意的是如果构造函数返回的是一个对象,就直接放回该对,否则返回我们想要的新对象。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,733评论 0 38
  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 9,667评论 0 13
  •   引用类型的值(对象)是引用类型的一个实例。   在 ECMAscript 中,引用类型是一种数据结构,用于将数...
    霜天晓阅读 4,775评论 0 1
  • 函数和对象 1、函数 1.1 函数概述 函数对于任何一门语言来说都是核心的概念。通过函数可以封装任意多条语句,而且...
    道无虚阅读 10,094评论 0 5
  • 當我們真心愛一個人時,會非常注意每一個細節,在乎到對方的感受。生害怕自己哪一點沒有做好,令到對方和自己相處的...
    落子无悔ss阅读 3,056评论 0 0