javascriptnode.jsthisglobal-scope

Different handling of 'this' in Node.js and Browser


I have Node.js v8.10.0 locally installed. I wrote a simple script to play with 'this':

var x = 1;

var fn = function (a) {
     var x = a;

     console.log(`local x = ${x}`);
     console.log(`global x = ${this.x}`);
}

fn(10);

When I execute script via Node.js I get following result:

local x = 10

global x = undefined

When I execute script in Chrome I get the following result:

local x = 10

global x = 1

Could you please explain to me, why Node.js doesn't see x in global scope?


Solution

  • Could you please explain to me, why Node.js doesn't see x in global scope?

    It does, if you run it in Node console. If you run it in as a file, x is in the file's scope, not global scope.

    By the way, in Node, you can use global to explicitly see the global scope, just like you'd use window in a browser. Thus,

    console.log(global == this)
    

    will give you two different answers depending on whether you run it in a file or in a console.

    Also, try to migrate to let and const. This is extra confusing because var behaves differently in global scope and elsewhere. In console and in browser, your outer var x is in global scope, so it defines a global variable (window.x and global.x). In a Node file, var x is not in a global scope, so it does what it normally does when not in global scope: defines a local variable x (not this.x, not global.x, just x). Thus, you have two local variables, the inner one shadowing the outer one, which makes the outer one inaccessible. Meanwhile, this.x has never been defined.