在 IntelliJi 中创建以下 Node.js 应用程序:
该应用程序将包含两个文件。 Students.js 文件和 app.js 文件。
在students.js文件中,将存在以下模块:
changeStudentInfo - 调用时会将学生姓名、学生编号、学生地址、学生城市、学生所在州和学生邮政编码存储到可由另一个函数访问的变量中。该信息从 app.js 程序传递到函数中。提示:观看“this 指针”视频和“模块”视频。
displayStudentInfo - 将显示在changeStudentInfo函数中设置的变量的内容。
app.js 文件将:
调用 displayStudentInfo 函数来显示每个变量的默认值。
调用changeStudentInfo函数将变量信息更改为您的信息。 (您可以使用虚假地址)。
调用displayStudentInfo函数显示更改后的值。
这是我到目前为止的学生文件
var info = {
name: "Default",
major: "Major",
sum: function(){
console.log(this.name);
console.log(this.major);
}
};
function changeStudentInfo() {
this.name = "Kita";
this.address = "CandyLane";
}
function displayStudentInfo(){
info.sum();
}
module.exports.studentinfo = displayStudentInfo;
module.exports.studentupdate = changeStudentInfo;
这是我在应用程序文件中的内容
var student = require('./student');
student.studentinfo();
student.studentupdate();
最佳答案
改成这个即可修改学生信息 -
function changeStudentInfo(name, address) {
info.name = name;
info.address = address;
}
然后从应用程序文件中调用此函数,如下所示 -
student.studentupdate('Kita', 'CandyLane');
在应用程序文件中执行此操作 -
var student = require('./student');
student.studentinfo();
student.studentupdate('Kita', 'CandyLane');
student.studentinfo();
关于javascript - Node.js 如何使用 this 和调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55089372/