练习题5_手动实现bind.html 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <script>
  10. // 第一步向Function.prototype上添加一个bind2方法
  11. // Function.prototype.bind2 = function (obj,...arg) {
  12. // // 返回一个函数
  13. // let that = this;
  14. // return function () {
  15. // // that.call(obj);
  16. // // that.apply(obj,arg);
  17. // that.call(obj,...arg);
  18. // }
  19. // }
  20. Function.prototype.bind2 = function (obj) {
  21. // 返回一个函数
  22. var that = this;
  23. // console.log(arguments.slice(1));
  24. // console.log(arguments);
  25. // console.log(Array.from(arguments));
  26. // var arg = Array.from(arguments);
  27. var arg = Array.prototype.slice.call(arguments,1);
  28. return function () {
  29. // that.call(obj);
  30. // that.apply(obj,arg);
  31. that.apply(obj,arg);
  32. }
  33. }
  34. function foo(x,y) {
  35. console.log(this.a,x,y)//hello
  36. }
  37. var obj = {
  38. a: "hello"
  39. }
  40. var foo2 = foo.bind2(obj,1,2);
  41. foo2()
  42. </script>
  43. </body>
  44. </html>