常用于约束一个函数及其函数的内外部属性:

    1. interface ICounter {
    2. (start: number): void,
    3. value: number,
    4. interval: number,
    5. add(): void,
    6. reset(): number,
    7. }
    8. function generateCounter(): ICounter {
    9. let originValue = 0;
    10. let counter = (function (start) {
    11. originValue = start;
    12. counter.reset();
    13. }) as ICounter;
    14. counter.add = function () {
    15. counter.value += counter.interval;
    16. }
    17. counter.reset = function () {
    18. counter.interval = 1;
    19. return counter.value = originValue;
    20. }
    21. return counter;
    22. }
    23. const myCounter: ICounter = generateCounter()
    24. console.log(myCounter)
    25. /**
    26. [Function: counter] {
    27. add: [Function (anonymous)],
    28. reset: [Function (anonymous)]
    29. }
    30. */
    31. myCounter(0)
    32. console.log(myCounter)
    33. /**
    34. [Function: counter] {
    35. add: [Function (anonymous)],
    36. reset: [Function (anonymous)],
    37. interval: 1,
    38. value: 0
    39. }
    40. */
    41. myCounter.add()
    42. console.log(myCounter)
    43. /**
    44. [Function: counter] {
    45. add: [Function (anonymous)],
    46. reset: [Function (anonymous)],
    47. interval: 1,
    48. value: 1
    49. }
    50. */
    51. myCounter.interval = 2
    52. console.log(myCounter)
    53. /**
    54. [Function: counter] {
    55. add: [Function (anonymous)],
    56. reset: [Function (anonymous)],
    57. interval: 2,
    58. value: 1
    59. }
    60. */
    61. myCounter.add()
    62. console.log(myCounter)
    63. /**
    64. [Function: counter] {
    65. add: [Function (anonymous)],
    66. reset: [Function (anonymous)],
    67. interval: 2,
    68. value: 3
    69. }
    70. */
    71. myCounter.reset()
    72. console.log(myCounter)
    73. /**
    74. [Function: counter] {
    75. add: [Function (anonymous)],
    76. reset: [Function (anonymous)],
    77. interval: 1,
    78. value: 0
    79. }
    80. */