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

相关文章
相关标签/搜索