this为什么会为undefined

3次阅读

共计 1520 个字符,预计需要花费 4 分钟才能阅读完成。

一、前言

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

五、进阶问题回答

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

正文完
 0