zoukankan      html  css  js  c++  java
  • 闭包模拟静态变量与私有变量

    模拟静态变量

    let Counter = (function () {
      // 闭包上下文
      let COUNTER = 0
      function changeBy (val) {
        COUNTER+=val
      }
      function Counter () {}
      Counter.prototype.increment = function () {
        changeBy(1)
      }
      Counter.prototype.decrement = function () {
        changeBy(-1)
      }
      Counter.prototype.value = function () {
        return COUNTER
      }
      return Counter
    })()
    
    let counter1 = new Counter()
    let counter2 = new Counter()
    console.log(counter1.value(),counter2.value()) // 0 0
    counter1.increment()               
    console.log(counter1.value(),counter2.value())  // 1 1
    

    上述的Counter可以看成一个名为Counter的类,这个类包含一些方法来增大、减小或读取COUNTER的值,COUNTER变量本身并不是对象原型的一部分,而Counter构造函数本身又是闭包的一部分。
    所以,所有Counter类的实例都共享同一个闭包上下文,这意味着这个上下文中的counter变量和changeBy函数将会表现的如同单例一样

    模拟私有变量

    let makeCounter = function () {
      // 闭包上下文
      let COUNTER = 0
      function changeBy (val) {
        COUNTER+=val
      }
      function Counter () {}
      Counter.prototype.increment = function () {
        changeBy(1)
      }
      Counter.prototype.decrement = function () {
        changeBy(-1)
      }
      Counter.prototype.value = function () {
        return COUNTER
      }
      return new Counter()
    }
    
    let counter1 = makeCounter()
    let counter2 = makeCounter()
    console.log(counter1.value(),counter2.value())  // 0 0
    counter1.increment()                   
    console.log(counter1.value(),counter2.value())  // 1 0
    

    当条用makeCounter函数时,一个新的闭包上下文被创建,所以每个新的实例都有独立的上下文

    总结

    通过上面的演练,我们可以联想到ES6的类属性、类方法以及私有属性、私有方法
    

    参考书籍:
    《Learning TypeScript中文版》

  • 相关阅读:
    采用二叉搜索树来统计文本中单词出现的频率
    一个表查找程序
    unix grep命令的大致实现
    字符串操作函数
    关于宏和逗号表达式
    http状态码的分类
    nginx源码学习资源(不断更新)转
    什么是CGI
    字符串操作 删除字符
    Ubuntu安装特定版本安装包
  • 原文地址:https://www.cnblogs.com/raind/p/10659023.html
Copyright © 2011-2022 走看看