为什么我的函数无法访问Node.js中的全局对象

时间:2019-04-23 15:46:11

标签: javascript node.js

在浏览器中执行此功能时,我会收到正确的预期消息

::text

但是在Node.js中执行此代码时,我在最后一句话中得到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();

undefined

为什么在Nodejs和浏览器中结果不一样?

1 个答案:

答案 0 :(得分:1)

最后一行实际结果是:

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

undefined是因为您没有为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();

我也真的建议不要使用this全局对象,我不确定为什么要使用它。