一、前言

普通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

Comments评论



也可直接在issue下评论 https://github.com/raoenhui/raoenhui.github.io/issues