admin管理员组

文章数量:1410717

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

var a = 2;

(function() {
  "use strict";

  foo(); // 2
})();

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

var a = 2;

(function() {
  "use strict";

  foo(); // 2
})();

I was just wondering, how e calling foo() still gives the value 2? I thought that since foo is called inside of an IIFE then this.a would evaluate to undefined, since there is no a variable in the IIFE.

Share edited Feb 7, 2021 at 7:38 Maulik 7951 gold badge8 silver badges23 bronze badges asked Feb 7, 2021 at 7:19 MarkMark 1832 silver badges8 bronze badges 2
  • I think because it is declared with var on the global scope. a bees a property of window object. – Ozgur Sar Commented Feb 7, 2021 at 7:27
  • 3 Strict mode matters in the location of the function definition, not in the location of the call. – Bergi Commented Feb 7, 2021 at 7:32
Add a ment  | 

4 Answers 4

Reset to default 7

The "use strict" is being applied to the IIFE, not the foo() function. As a result, foo gets ran in sloppy mode/non-strict mode. Since foo() doesn't get an explicit this bound to it, it defaults to the global object, which in browsers is the window. When you declare var a in the global scope, it gets added to the window object as a property, meaning using this.a inside of foo will give you the value held in a, as it's accessing the a property of the window.

You would get undefined for this if foo() was being run in strict mode, not the IIFE:

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

var a = 2;

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

that is because both foo and a are declared in the global scope that is they are properties of the global object window.

the this inside IIFE itself will be undefined because it is in strict mode. but calling foo inside the IIFE will make this inside the foo refer to the window object.

and since you already have a in window it get printed out.

Let's see two things here :-

Firstly your strict mode can apply to globalThis when it's declared in that scope, like so :-

"use strict";

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

var a = 2;

(function() {
  foo(); // Throws error since this is undefined
})();

Another way could be how @Nick proposed it to run only foo in strict mode.

Now secondly,

The this inside your IIFE is your globalThis which is window for browsers. Variables declared with var in global scope attach themselves to window.

function test(){
   return {
      a: 9999,
      testFunc: foo
   }
}
  
function foo() {
  console.log(this)  //this is actually another context which point to its parent.
  console.log(this.a);
}

var a = 2;

(function() {
  "use strict";
  console.log(this) //because of 'use strict', this will lead to undefined
  foo(); // 2
  test().testFunc(); //9999
})();

本文标签: javascript39this39 keyword context inside of a IIFEStack Overflow