0

I wrote a code which I can't understand why it prints undefined. I was expecting to see "oops, global" because the call to foo is not from the object so it must be from the global scope which means that the this refers to the global this.

Where am I wrong?

var obj1 = {
    a123: 2,
    foo: function() {
        // console.log(this); obj1 is not in this. why?
        console.log(this.a123);
    }
};

var a123 = "oops, global";
var f = obj1.foo;
f(); // prints undefined. why? should have printed "oops, global"

I'm running the code in IntelliJ using nodejs.

Stav Alfi
  • 10,681
  • 15
  • 74
  • 124

3 Answers3

2

Because in node js this means module.export if you are in outer scope. In browser this means window. This is the difference.

See this Meaning of "this" in node.js modules and functions

user2693928
  • 3,158
  • 1
  • 11
  • 19
1

This can be a little confusing in Node because you are dealing with two different scopes from the beginning.

Node has a global object. Variables assigned without var, let, const will be assigned to this object. When you start a process, however, there is also a module-level scope. Variables assigned with var, let, const live in this scope. This is an important feature that keeps variables from different modules from clashing.

In you example, when you run f(), this points to global. But your variable a123 is not defined on global. You can assign it explicitly and you will see the behavior your expect with:

global.a123 = "oops, global"

This is the same as assigning without var, etc.

Outside of a function this refers to module.exports. For example:

module.exports.foo = 'bar'
console.log(this) // >> { foo: 'bar' }
Mark
  • 74,559
  • 4
  • 81
  • 117
0

Else, if you want to access the obj1 from this, you have to remove the local declaration.

for example, instead of

var obj1 = {};

you could use

obj1 = {} //it will add obj1 to this scope (window scope)
jithil
  • 651
  • 6
  • 8