bind

bind() 预先处理机制

  1. export function bind(func, object, ...args) {
  2. if(object == null) {
  3. object = globalThis; // es11中的全局对象
  4. }
  5. // bind 返回一个新函数,调用目标函数,改变其 this指向
  6. return (...args2) => {
  7. return func.call(object, ...args, ...args2);
  8. }
  9. }
  10. function add(a,b) {
  11. console.log(this);
  12. return a + b + this.c;
  13. }
  14. const obj = { c: 100 }
  15. window.c = 200;
  16. const fn = bind(add, obj, 10, 20);
  17. const fn2 = bind(add, obj);
  18. fn2(100, 200)

call

call改变函数的 this指向

  1. export function call(func, object, ...args) {
  2. if(object == null) {
  3. object = globalThis; // es11中的全局对象
  4. }
  5. // 添加临时方法
  6. object.temp = func;
  7. const result = object.temp(...args);
  8. delete object.temp;
  9. return result;
  10. }
  11. function add(a,b) {
  12. console.log(this);
  13. return a + b + this.c;
  14. }
  15. const obj = { c: 100 }
  16. window.c = 200;
  17. call(add, obj, 10, 20);
  18. call(add, null, 10, 20)

apply

apply 改变函数的 this指向, []

  1. export function apply(func, object, args) {
  2. if(object == null) {
  3. object = globalThis; // es11中的全局对象
  4. }
  5. // 添加临时方法
  6. object.temp = func;
  7. const result = object.temp(...args);
  8. delete object.temp;
  9. return result;
  10. }
  11. function add(a,b) {
  12. console.log(this);
  13. return a + b + this.c;
  14. }
  15. const obj = { c: 100 }
  16. window.c = 200;
  17. apply(add, obj, [10, 20]);
  18. apply(add, null, [10, 20])