匿名函数、构造函数中的this
直接上测试代码:
//直接调用 function outer(){ console.log(this); //this ==> window (function inner(){ console.log(this); //this ==> window })(); }; outer(); //函数返回undefined
//通过构造函数调用 function outer(){ console.log(this); //this ==> outer (function inner(){ console.log(this); //this ==> window })(); }; new outer(); //构造函数返回outer
//在obj对象下直接调用 function outer(){ console.log(this); //this ==> obj对象 (function inner(){ console.log(this); //this ==> window })(); }; var obj = {}; obj.o = outer; obj.o(); //函数返回undefined
//在obj对象下通过构造函数调用 function outer(){ console.log(this); //this ==> outer (function inner(){ console.log(this); //this ==> window })(); }; var obj = {}; obj.o = outer; new obj.o(); //构造函数返回outer
小结:
- this始终指向一个对象,基于函数的执行环境绑定的
- 全局环境中,this等于window
- 当函数被作为某个对象的方法调用时,this等于那个对象
- 构造函数会生成一个新的对象,其内部的this指向这个对象
- 匿名函数的执行环境具有全局性,因此其this对象通常指向window。每个函数在被调用时,其活动对象都会自动取得两个特殊变量:this和arguments。内部函数在搜索这两个变量时,只会搜索到其活动对象为止,因此永远不可能直接访问外部函数中的这两个变量。不过,把外部作用域中的this对象保存在一个闭包能够访问到的变量里。就可以让闭包访问该对象了。
- 最后,感谢这个链接的答主,让我加深了对this的理解:https://segmentfault.com/q/1010000004648772

浙公网安备 33010602011771号