this爲什麼會爲undefined?

一、前言

普通function定義的函數

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

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

箭頭函數

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

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

二、問題點: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>

三、回答

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

image.png

用了嚴格模式"use strict"嚴格模式下無法再意外創建全局變量
),所以this不爲window而爲undefined

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

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

嚴格模式爲什麼對箭頭函數沒有效果,返回還是window

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

五、進階問題回答

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.

綜上所述,在箭頭函數中,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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章