K.M.J
K.M.J

Reputation: 143

Why my function is not able to access the global object in Nodejs

When executing this function in the browser I get a correct and expected message

function displayInformation() {
  console.log("student with " + this.rollNo + " is " + this.name + " who is in class: " + this.class + " and he is of " + this.subject + " stream ")
};

var student1 = {
  rollNo: 100,
  name: "Rajiv",
  class: 10,
  subject: "PCMC",
  display: displayInformation
};

var student2 = {
  rollNo: 101,
  name: "Sam",
  class: 11,
  subject: "PCMB",
  display: displayInformation
};

var student3 = {
  rollNo: 102,
  name: "Ghanshyam",
  class: 12,
  subject: "commerce",
  display: displayInformation
};

student1.display();
student2.display();
student3.display();

this.name = "Raju";
this.age = 28;
this.rollNo = 103;
this.class= 123;
this.subject = "Arts";

displayInformation();

However when executing this code in Nodejs I am getting undefined in the last sentence:

student with 100 is Rajiv who is in class: 10 and he is of PCMC stream
student with 101 is Sam who is in class: 11 and he is of PCMB stream
student with 102 is Ghanshyam who is in class: 12 and he is of commerce stream
student with undefined is undefined who is in class: undefined and he is of undefined stream

Why is the result not the same in Nodejs and the Browser?

Upvotes: 0

Views: 60

Answers (1)

Lolpez
Lolpez

Reputation: 879

The last line actual result is:

student with 103 is Raju who is in class: undefined and he is of Arts stream 

The undefined is because you didn't assign a value to this.class

function displayInformation() {
  console.log("student with " + this.rollNo + " is " + this.name + " who is in class: " + this.class + " and he is of " + this.subject + " stream ")
};

this.name = "Raju";
this.age = 28;
this.rollNo = 103;
this.subject = "Arts";
this.class = 123; // <-- You missed this

displayInformation();

Also I really recommend to not use the this global object, I am not sure why are you using it.

Upvotes: 2

Related Questions