Naor Tedgi
Naor Tedgi

Reputation: 5707

this keyword acts different between NodeJS and Vanila JavaScript

I'm trying to learn about JavaScript lexical scoping and closures. I ran this example using Node.js and then in the browser and got 2 different outputs.

tested on chrome Version 80.0.3987.149 (Official Build) (64-bit)
and Node v12.16.1

var obj1 = {
        name: "Pulsar",
        bike: function() {
          console.log(this.name);
        }
      }
      var obj2 = { name: "Gixxer", bike: obj1.bike };
      var name = "Ninja";
      var bike = obj1.bike;
      
      bike();           // "Ninja"
      obj1.bike();      // "Pulsar"
      obj2.bike();      // "Gixxer"

This snippet of code acts differently in Vanilla JavaScript. The output is:

Ninja 
Pulser
Gixxer

and in NodeJS the output is:

undefined
Pulsar
Gixxer

can someone please explain?

Upvotes: 1

Views: 86

Answers (2)

Yosef Tukachinsky
Yosef Tukachinsky

Reputation: 5895

In browsers the top-level scope is the global scope. It means that when you define something with var it becomes a property of the global object, which is window.

So bike and name are both defined in a global scope, which means they both are window properties, so this points to the window and it has a name property, with the value Ninja.

In node, any var in the global scope is defined in a different local module, so the this of the bike is not related to a name variable

Upvotes: 3

Peri
Peri

Reputation: 574

In a browser, the window object is the global this object and all variables get assigned as its property. In node, there is no such object. There is a this ( {} ), globalThis and module, but the module variables do not get assigned to them, instead they are assigned in memory.

Upvotes: 1

Related Questions