javascript - 为什么我的函数无法访问 Nodejs 中的全局对象

标签 javascript 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();

但是,当在 Nodejs 中执行此代码时,我在最后一句中得到 undefined:

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

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

最佳答案

最后一行实际结果是:

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

未定义是因为您没有为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 全局对象,我不确定你为什么使用它。

关于javascript - 为什么我的函数无法访问 Nodejs 中的全局对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55814954/

相关文章:

json - 访问 Node.js 中的 JSON 位置

javascript - 使用 Node.js 读取 sqlite3 表

javascript - AngularJS $http.get 中的返回 promise ?

node.js - res.cookie未在浏览器中设置cookie

javascript - 使用其参数调用 Angular js 中的函数

javascript - 如何计算某个名字出现的次数?

javascript - 通过 html 内容选择 javascript/jquery 中的元素

javascript - 如何使用链接在输入选项卡之间导航?

javascript - 使用 Angular 和 ng-model 更改模型时,不会更新 Materialise select

javascript - 如何在执行时运行 gulp 任务