javascript - Node.js 如何使用 this 和调用函数

标签 javascript node.js intellij-idea

在 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/

相关文章:

javascript - 这是对总结对象数组有益的 JavaScript 重构吗?

javascript - 在foreach中请求api

intellij-idea - java Spring Jet Brains Idea Autowiring sessionFactory 检查

java - IDEA 10.5 命令行太长

javascript - 标记聚类器

javascript - Jquery 悬停延迟

javascript - Node.js Express 没有响应

json - 将 Json 文件导入 Mongoose

javascript - Amazon Cloud (AWS) 中的代码-测试-代码周期

intellij-idea - 如何使用注释禁用代码某些部分的代码格式?