why this inside function refers to global object in node when function itself is not defined on global?

NodeJs:

function foo() {
  console.log(this === global); // true
  }
foo();
console.log(global.foo); //undefined

this inside a function refers to the object on which function was invoked. So from above code I expect foo to exist on global object but that is not the case. Can anyone explain this behaviour?

1 answer

  • answered 2020-09-26 13:54 jfriend00

    In non-strict mode in Javascript (often called "loose" mode), when you call a function as a regular function such as foo(), the this value will be set to the global object.

    In strict mode in Javascript, when you call a function as a regular function such as foo(), the this value will be set to undefined.

    Based on the results in your question, you are apparently running in non-strict mode so the this value inside your function is set to the global object when called as foo(). The function declaration itself in node.js is inside a module so that function has module scope, not global scope and thus the function itself is not a property of the global object. The this value has only to do with the fact that it was called as foo() in non-strict mode.

    Keep in mind that the this value in a function in Javascript is entirely determined by how the function was called (and in the case of arrow functions, how it was declared). You can see the six ways that the value of this is controlled or determined inside a function call here in this answer.


    Now, for your specific questions:

    this inside a function refers to the object on which function was invoked.

    That would be true if the function was called as in obj.foo() and foo was defined as a property of object obj. But, that does not apply when it is called as foo() and foo is declared as a stand-alone function (not a property on a specific object).

    So from above code I expect foo to exist on global object but that is not the case. Can anyone explain this behaviour?

    Whether foo exists on the global object or not is determined by how foo is defined, not how it is called. It has to either be specifically assigned to the global object or declared in the global scope. In your specific example in node.js, foo is declared within module scope (which is actually within a module function) so it is local to that module scope and is not global.