globalThis
image.png

call

参数是一个一个的传递
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call

  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. }

use

  1. function add(a,b) {
  2. console.log(this);
  3. return a + b + this.c;
  4. }
  5. const obj = { c: 100 }
  6. window.c = 200;
  7. call(add, obj, 10, 20);
  8. call(add, null, 10, 20)

apply

参数是个数组
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

  1. // apply 改变函数的 this指向, []
  2. export function call(func, object, args) {
  3. if(object == null) {
  4. object = globalThis; // es11中的全局对象
  5. }
  6. // 添加临时方法
  7. object.temp = func;
  8. const result = object.temp(...args);
  9. delete object.temp;
  10. return result;
  11. }

bind

创建一个新函数,并返回这个新函数,
不会执行这个函数,只是返回新函数,需要手动执行
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/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. }

use

  1. function add(a,b) {
  2. console.log(this);
  3. return a + b + this.c;
  4. }
  5. const obj = { c: 100 }
  6. window.c = 200;
  7. const fn = bind(add, obj, 10, 20);
  8. const fn2 = bind(add, obj);
  9. fn2(100, 200)