闭包 作用域 this that
对于闭包的痛点在于,闭包的this默认绑定到window对象,但又常常需要访问嵌套函数的this,所以常常在嵌套函数中使用var that = this,然后在闭包中使用that替代this,使用作用域查找的方法来找到嵌套函数的this值
function foo() { setTimeout(() => { console.log( this.a ); },100); } var obj = { a: 2 }; foo.call( obj ); // 2
等同于:
//等价于 function foo() { var that = this; setTimeout( function(){ console.log( that.a ); }, 100 ); } var obj = { a: 2 }; foo.call( obj ); // 2