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
  • 相关阅读:
    怎么用js实现jq的removeClass方法
    减少事件绑定次数
    JS setAttribute兼容
    css3常用动画+动画库
    小tip: transition与visibility
    image的srcset属性
    jqeury点击空白关闭弹窗
    卡片翻转效果
    div+css 圆角加阴影
    函数
  • 原文地址:https://www.cnblogs.com/wsblm/p/14493307.html
Copyright © 2011-2022 走看看