closure.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. function fn1(a, b) {
  2. console.log('this : ', this);
  3. console.log(a, b);
  4. return a + b;
  5. }
  6. // const result = fn1(1, 2);
  7. // console.log(result);
  8. // const fn2 = fn1.bind({name: 'yibo'});
  9. // const result = fn2(1, 2);
  10. // 自己实现bind方法
  11. Function.prototype.bind2 = function () {
  12. const _this = this; // 这是函数对象的this
  13. const arr = Array.prototype.slice.call(arguments);
  14. const t = arr.shift();
  15. return function () {
  16. return _this.apply(t, arr);
  17. }
  18. }
  19. // const fn2 = fn1.bind2({name: 'yibo'}, 6, 7);
  20. // const result = fn2();
  21. // console.log(result);
  22. // 自己实现call方法
  23. Function.prototype.myCall = function (context) {
  24. if(context == null){
  25. context = window;
  26. }
  27. context.fn = this;
  28. const arg = [...arguments].slice(1);
  29. const ret = context.fn(...arg);
  30. delete context.fn;
  31. return ret;
  32. }
  33. // const result = fn1.myCall({name: 'jal'}, 150, 100);
  34. // console.log(result);
  35. // 自己实现apply方法
  36. Function.prototype.myApply = function (context, arr) {
  37. if(context == null) {
  38. context = window;
  39. }
  40. context.fn = this;
  41. let ret;
  42. if(arr == null){
  43. ret = context.fn();
  44. }else {
  45. ret = context.fn(...arr);
  46. }
  47. delete context.fn;
  48. return ret;
  49. }
  50. // const result = fn1.myApply({name: 'cathy'}, [2, 4]);
  51. // console.log(result);
  52. // 自己实现bind方法
  53. Function.prototype.myBind = function (context) {
  54. if(context == null){
  55. context = window;
  56. }
  57. const arg = [...arguments].slice(1);
  58. const _this = this;
  59. return function F () {
  60. if(this instanceof F) {
  61. return _this.call(this, ...arg);
  62. }
  63. return _this.call(context, ...arg);
  64. }
  65. }
  66. // const fn2 = fn1.myBind({name: 'yibo'}, 6, 7);
  67. // const result = fn2();
  68. // console.log(result);
  69. function f() {
  70. const data = {};
  71. return {
  72. get: function (key) {
  73. return data[key];
  74. },
  75. set: function (key, value) {
  76. data[key] = value
  77. }
  78. }
  79. }
  80. const cache = f();
  81. cache.set('name', 'yibo');
  82. console.log(cache.get('name'));