zoukankan      html  css  js  c++  java
  • [TS]闭包测试

    class sss
    {
        public name = "emiya";
        constructor(){
            console.log("new sss");
        }
        private test()
        {
            let nowName = this.name;
            setTimeout(() => {
                console.log(this);
                console.log(nowName);
                this.name = nowName;
                console.log("now is old nowName");
            }, 1000);
        }
    
        public ss(){
            this.test();
            console.log("change name wisdom");
            this.name = "wisdom";
            this.test();
            setTimeout(() => {
                console.log(this.name);
            }, 3000);
        }
    }
    
    let s = new sss();
    s.ss();
    s = null;
    

      运行结果如下:

    [Running] ts-node "c:Users11418Desktopclass sss.ts"
    new sss
    change name wisdom
    sss { name: 'wisdom' }
    emiya
    now is old nowName
    sss { name: 'emiya' }
    wisdom
    now is old nowName
    wisdom
    

      

    最开始nowName临时变量被赋值emiya,由于闭包数据一直留着。之后name被切换成wisdom。计时器1s到了后匿名函数输出之前存的临时变量,值为emiya,再向上寻找到this(name在1s前被改)。之后输出类似,最后name被改为wisdom
  • 相关阅读:
    c/c++指针数组和数组指针
    c/c++指针传参
    c/c++指针理解
    c/c++容器操作
    c/c++ 数组传参
    c/c++ 结构体传参问题
    c++ 创建对象的三种方法
    c/c++ 随机数生成
    c++预处理指令
    团队冲刺第二阶段01
  • 原文地址:https://www.cnblogs.com/wsblm/p/14493307.html
Copyright © 2011-2022 走看看