直接上代码
<script type="text/javascript">
'use strict';
console.log(this === window); // true
var foo = function() {
console.log(this === window);
console.log('this:',this);
};
foo();
window.foo();
</script>
我了个去,小俞的正确答案居然被忽略了,还写了个:答非所问。
我也是醉了。
如果没有"use strict"
foo中的this就是window
你用了"use strict", foo中的this指向window是被禁止的,但是除了window之外,foo中又没有其他作用域链了,所以this就是undefined。
所以:
this === window // false
this === undefined // true
因为你声明了严格模式
'use strict';
严格模式下,禁止this关键字指向全局对象
是 use strict
的问题,严格模式下禁止 this
指向全局变量,参见:http://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html
看语言精粹里说一般函数this的设定是语言设计上的一个错误,如果设计正确,那么内部函数被调用时this应该指向外部函数的this变量。所以,我之前也觉得一般的函数这个this有点蛋疼的,无法理解。
函数没有明确返回值的情况下,都是返回undefined的
和函数的返回值或者console.log的返回值没什么关系;这里是因为有"use strict"
,在严格模式下,重新规定了执行上下文中的this
,禁止函数中this关键字指向全局对象,直接foo()
这样的话,函数中this就是undefined。反之,如果不使用严格模式,那么this就是window了。可以参见阮一峰的这篇 http://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html