[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:\Users\11418\Desktop\class 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