Daily-Question icon indicating copy to clipboard operation
Daily-Question copied to clipboard

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

Open shfshanyue opened this issue 3 years ago • 2 comments

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

var a = 2;

(function(){
  "use strict";

  foo();
})();

shfshanyue avatar Jun 03 '21 02:06 shfshanyue

输出: 2

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

shfshanyue avatar Jun 03 '21 02:06 shfshanyue

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

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

var a = 2;

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

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

ridershoot avatar Jul 13 '22 15:07 ridershoot