javascript - 直接调用类而不是通过实例变量

标签 javascript node.js

我在我的 classes.js 中创建了以下两个类:

class Person {
    constructor(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    display() {
        console.log(this.firstName + " " + this.lastName);
    }
}

module.exports = {
    Person
};

如您所见,我正在通过 module.exports 导出这两个类。

Person = require('./classes.js');

const someone1 = new Person("First name", "Last name"); // <-- does NOT work

const someone = new Person.Person("First name", "Last name"); // does work
someone.display();

但是,当直接调用类时调用类时出现错误。

有什么建议可以直接调用类吗?

感谢您的回复!

最佳答案

如果您希望将所有类放在一个名为 classes.js 的文件中,那么这应该可行;

// classes.js

class Person {
  // ...
}

class Vehicle {
  // ...
}

module.exports = {
  Person,
  Vehicle
}
// some-other-file.js

const { Person } = require('../classes')

const person = new Person('First', 'Last')

虽然为了让事情容易理解,我的建议是将您的类拆分为多个文件,然后直接从其文件中导出每个类;

class Person {
  // ...
}

module.exports = Person
const Person = require('../classes/person')

// do something

关于javascript - 直接调用类而不是通过实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55686178/

相关文章:

javascript - 如何将一些 HTML/文本添加到 Javascript 文本输出中?我似乎只能要么只做 JS,要么只做文本,不能两者兼而有之

node.js - 在收到用户输入之前如何阻止?

node.js - nodejs oracledb 从回调中获取数据

node.js - Nest 无法解析 RegisterService 的依赖关系(?)。请确保索引 [0] 处的参数在 RegisterModule 上下文中可用

javascript - "attempt to run compile-and-go script on a cleared scope"- Drupal 使用 Google Graph api 时出错

javascript - 多次实例化@ViewChild,这样我就可以再次使用HTML Angular 4

javascript - 在网络墨卡托中以任意浮点缩放级别转换纬度/经度和像素?

javascript - angularjs:指令和 ng-repeat

ajax - node.js 表达 ajax session

node.js - 异步 I/O 和异步函数有什么区别?