call

  1. function (context, ...args) {
  2. if (!context || context === null) {
  3. context = window;
  4. }
  5. // 创造唯一的key值 作为我们构造的context内部方法名
  6. let fn = Symbol();
  7. context[fn] = this; //this指向调用call的函数
  8. // 执行函数并返回结果 相当于把自身作为传入的context的方法进行调用了
  9. return context[fn](...args);
  10. };

apply

  1. function (context, args) {
  2. if (!context || context === null) {
  3. context = window;
  4. }
  5. // 创造唯一的key值 作为我们构造的context内部方法名
  6. let fn = Symbol();
  7. context[fn] = this;
  8. // 执行函数并返回结果
  9. return context[fn](...args);
  10. };

bind

  1. function (context, ...args) {
  2. if (!context || context === null) {
  3. context = window;
  4. }
  5. // 创造唯一的key值 作为我们构造的context内部方法名
  6. let fn = Symbol();
  7. context[fn] = this;
  8. let _this = this;
  9. // bind情况要复杂一点
  10. const result = function (...innerArgs) {
  11. // 第一种情况 :若是将 bind 绑定之后的函数当作构造函数,通过 new 操作符使用,则不绑定传入的 this,而是将 this 指向实例化出来的对象
  12. // 此时由于new操作符作用 this指向result实例对象 而result又继承自传入的_this 根据原型链知识可得出以下结论
  13. // this.__proto__ === result.prototype //this instanceof result =>true
  14. // this.__proto__.__proto__ === result.prototype.__proto__ === _this.prototype; //this instanceof _this =>true
  15. if (this instanceof _this === true) {
  16. // 此时this指向指向result的实例 这时候不需要改变this指向
  17. this[fn] = _this;
  18. this[fn](...[...args, ...innerArgs]); //这里使用es6的方法让bind支持参数合并
  19. } else {
  20. // 如果只是作为普通函数调用 那就很简单了 直接改变this指向为传入的context
  21. context[fn](...[...args, ...innerArgs]);
  22. }
  23. };
  24. // 如果绑定的是构造函数 那么需要继承构造函数原型属性和方法
  25. // 实现继承的方式: 使用Object.create
  26. result.prototype = Object.create(this.prototype);
  27. return result;
  28. };