一、前言
普通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文件上加上嚴格模式。
用了嚴格模式"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>
五、進階問題回答
lexical means that this refers to the this value of a lexically enclosing function.
綜上所述,在箭頭函數中,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