‘運行環境’也是對象,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