‘运行环境’也是对象,this
指向运行时所在的对象。 以下:javascript
若是一个函数在全局环境运行,this就指向顶层对象(浏览器中为window对象); 若是一个函数做为某个对象的方法运行,this就指向那个对象; 若是一个函数做为构造函数,this指向它的实例对象。html
函数体内的this
对象,就是定义时所在的对象,而不是使用时所在的对象。java
原本记住这几点已经能够了,this
最终找到是可能window
,可是undefined
是怎么又是怎么来的,本妹子下面将一步步分析。es6
综上所述,this指向运行时所在的对象或指向定义时所在的对象,可是这个对象可能最后找到是window
,但都不多是undefined
,那么undefined
是怎么来的呢?浏览器
<html>
<script type="text/javascript"> var foo = function foo() { console.log(this); }; var foo1 = () => { console.log(this); }; foo(); //Window foo1(); //Window </script>
</html>
复制代码
咱们通常写js文件都是babel
转成ES6
的,babel
会自动给js文件上加上严格模式。babel
用了严格模式**"use strict"**,严格模式下没法再意外建立全局变量,因此this
不为window
而为undefined
app
<html>
<script type="text/javascript"> "use strict"; var foo = function foo(){ console.log(this) }; foo();//undefined </script>
</html>
复制代码
严格模式为何对箭头函数没有效果,返回仍是window
?frontend
<html>
<script type="text/javascript"> "use strict"; var foo = () => { console.log(this) }; foo(); //Window </script>
</html>
复制代码
lexical means that this refers to the this value of a lexically enclosing function. ui
综上所述,在箭头函数中,this
为lexical
类型,lexical
意味着这个this
指是所在封闭函数中this
,因此严格模式会自动忽视use strict
,因此this
以下所示:
<html>
<script type="text/javascript"> var foo = () => { "use strict"; console.log(this) }; foo(); //Window </script>
</html>
复制代码
箭头函数中,this
指向运行时所在的对象,而use strict
被移到函数内了,因此this
为全局变量window
。
Happy coding ~~ ^ ^
ECMAScript 2015 Language Specification – ECMA-262 6th Edition
use strict in javascript not working for fat arrow? - Stack Overflow