this爲何會爲undefined?

1、前言

普通function定義的函數

‘運行環境’也是對象,this指向運行時所在的對象。 以下:javascript

若是一個函數在全局環境運行,this就指向頂層對象(瀏覽器中爲window對象); 若是一個函數做爲某個對象的方法運行,this就指向那個對象; 若是一個函數做爲構造函數,this指向它的實例對象。html

箭頭函數

函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。java

原本記住這幾點已經能夠了,this最終找到是可能window,可是undefined是怎麼又是怎麼來的,本妹子下面將一步步分析。es6

2、問題點:undefined是怎麼來的

綜上所述,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>
複製代碼

3、回答

咱們通常寫js文件都是babel轉成ES6的,babel會自動給js文件上加上嚴格模式。babel

image.png

用了嚴格模式**"use strict"**,嚴格模式下沒法再意外建立全局變量,因此this不爲window而爲undefinedapp

<html>
<script type="text/javascript"> "use strict"; var foo = function foo(){ console.log(this) }; foo();//undefined </script>
</html>
複製代碼

4、進階問題:嚴格模式對箭頭函數沒有效果

嚴格模式爲何對箭頭函數沒有效果,返回仍是windowfrontend

<html>
<script type="text/javascript"> "use strict"; var foo = () => { console.log(this) }; foo(); //Window </script>
</html>
複製代碼

5、進階問題回答

Given that this comes from the surrounding lexical context, strict mode rules with regard to this are ignored.函數

lexical means that this refers to the this value of a lexically enclosing function. ui

綜上所述,在箭頭函數中,thislexical類型,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 ~~ ^ ^

相關連接

原文地址

嚴格模式 - JavaScript

Arrow functions - JavaScript

ECMAScript 2015 Language Specification – ECMA-262 6th Edition

函數的擴展 - ECMAScript 6入門

use strict in javascript not working for fat arrow? - Stack Overflow

相關文章
相關標籤/搜索