1

Following MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

If not in strict mode 'this' in a function will point to the global object.

However When trying to modify global variable in a function it does not work as I imagined. Is there some explanation to this or a spec one can refer to?

// this.somevariable = 'this is in global var'; // will not be in Global
somevariable = 'this is in global var'; // will make it to global


function something() {
    somebar = 'foo'; // this will not change the global variable
    this.somebar = 'foo'; // this will not change the global variable
    console.log(this.somevariable);
}

something();

console.log( this.somebar ); // somebar undefined

P.S I am just trying to figure out how 'this' keyword works. I understand that modifying global variables is a bad idea as well as not using strict mode.

*Running in node v10.14

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
Phil15
  • 515
  • 5
  • 14
  • 1
    Did you mean "somebar" and "somevariable" to be the same in your post? – Scala Enthusiast Apr 18 '19 at 08:13
  • 1
    Possible duplicate of [Meaning of "this" in node.js modules and functions](https://stackoverflow.com/questions/22770299/meaning-of-this-in-node-js-modules-and-functions) – JJJ Apr 18 '19 at 08:13

2 Answers2

2

If a function is not boxed, this is a global in sloppy mode and undefined in strict mode inside a function.

this refers to module object (module.exports) in Node.js module scope.

The difference is that this refers to a module here:

console.log(this.somebar); // this === module.exports

And refers to a global here:

console.log(this.somevariable); // this === global
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
-1

i think this example can explain you all:

// in node
function somethingNode() {
    console.log(global === this);
}

// in Browser
function somethingBrowser() {
    console.log(window === this);
}

somethingNode(); // true
somethingBrowser(); // true

in your last string you refer to module.exports object that's why it's not equal

Vadim Hulevich
  • 1,803
  • 8
  • 17