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