0

I copied the code from YDKJS(https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/up%20%26%20going/ch2.md)

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

var bar = "global";

var obj1 = {
    bar: "obj1",
    foo: foo
};

var obj2 = {
    bar: "obj2"
};

// --------

foo();              // "global"
obj1.foo();         // "obj1"
foo.call( obj2 );       // "obj2"
new foo();          // undefined

explained here that: foo() ends up setting this to the global object in non-strict mode -- in strict mode, this would be undefined and you'd get an error in accessing the bar property -- so "global" is the value found for this.bar.

why in strict mode, foo(); will be undefined?

maryam
  • 161
  • 1
  • 1
  • 14
  • have a look at this https://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it – Gulam Hussain Nov 16 '19 at 07:50
  • I think it's a matter of defining `var bar = "global"` Variables should not be globally defined! – maryam Nov 16 '19 at 07:58

1 Answers1

1

This is because of boxing in JS. The value passed as this to a function in strict mode is not forced into being an object. JS changes the this object when entering the context of the foo() function. In your sample code you are not calling the function as a part of an object, so its value will be undefined. If you do not use strict mode, the value of this is automatically set to the window object. more info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

Sylens
  • 1,097
  • 8
  • 31