在浏览器中执行此功能时,我会收到正确的预期消息
::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和浏览器中结果不一样?
答案 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
全局对象,我不确定为什么要使用它。