在浏览器中执行此函数时,我收到正确且预期的消息
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/