高级前端
js
【Q574】关于 this,判断以下代码输出

关于 this,判断以下代码输出

更多描述

function foo() {
  console.log(this.a);
}
 
var a = 2;
 
(function () {
  "use strict";
 
  foo();
})();

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 589 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

输出: 2

只有在存在 this 的函数中设置严格模式,this 为 undefined。因此此时会正常输出。

Author 回答者: ridershoot (opens in a new tab)

山月老师,应该是“只有在存在 this 的函数前设置严格模式,this为undefined。”才对。

"use strict";
function foo() {
  console.log( this.a );
}

var a = 2;

(function(){
  foo();
})();

按以上代码执行,函数foo中的this就不能指向window了。 不应该只是在函数中,在函数前设置严格模式thisundefined