call

  1. function call(fn, obj, ...arg) {
  2. //call 在非严格模式下,obj为null或者undefined时,this指向globalThis
  3. if (obj === undefined || obj === null) {
  4. obj = globalThis
  5. }
  6. //给obj添加临时方法
  7. obj.temp = fn
  8. //调用temp方法
  9. let res = obj.temp(...arg)
  10. //删除临时方法
  11. delete obj.temp
  12. //返回res
  13. return res
  14. }
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Document</title>
  8. <script src="./index.js"></script>
  9. </head>
  10. <body>
  11. <script type="text/javascript">
  12. function add(a, b) {
  13. console.log(this)
  14. return a + b + this.c
  15. }
  16. let obj = {
  17. c: 521
  18. }
  19. window.c = 1234
  20. console.log(call(add, obj, 10, 20))
  21. console.log(call(add, null, 10, 20))
  22. </script>
  23. </body>
  24. </html>

image.png

apply

function apply(fn, obj, arg) {
  //call 在非严格模式下,obj为null或者undefined时,this指向globalThis
  if (obj === undefined || obj === null) {
    obj = globalThis
  }
  //给obj添加临时方法
  obj.temp = fn
  //调用temp方法
  let res = obj.temp(...arg)
  //删除临时方法
  delete obj.temp
  //返回res
  return res
}

bind

function bind(fn, obj, ...arg) {
  return function () {
    return call(fn, obj, ...arg)
  }
}