【发布时间】:2020-07-19 11:40:20
【问题描述】:
这是一个基本问题,但这提出了一个有趣的问题。 例如,
var Foobar = function(){
this.baz = 100;
this.timer = null;
this.printLazy = function(){
this.timer = setTimeout(function(){
console.log(this.baz); //correctly bind this.
}.bind(this), 1000);
}
}
创建一个传统类,我们可以创建实例并调用printLazy as
var myBar = new Foobar();
myBar.printLazy();
现在在上面的代码中,printLazy 方法设置了一个计时器,我们在其中访问了this。
同样的事情可以使用捕获来实现,
this.printLazy = function(){
var self = this; //capture this.
this.timer = setTimeout(function(){
console.log(self.baz); //correctly bind this.
}, 1000);
}
- 这些方法中的一种是否比另一种更好? (考虑效率或性能)
- 第二个方法是否会导致内存泄漏,如果它被调用让我们说 1000 次或更多次快速连续,其中 self 将被函数内的其他部分引用?
【问题讨论】:
-
使用箭头函数 ``` var Foobar =()=>{ let baz = 100;让计时器=空; this.printLazy = ()=>{ setTimeout(()=>{ console.log(baz); //正确绑定 this. }, 1000); } }```
-
是的。箭头函数为此使用了正确的范围。但我期望的是一个更理论的解释,涉及 es5 风格的答案,涉及捕获与绑定。
标签: javascript variables scope