1

I have this in MyClass.js:

function MyClass(name) {
    this.Name = name;
}

module.exports.MyClass = MyClass;

And I have this in Main.js:

var MyClass = require('./MyClass');

var obj = new MyClass('Something');

console.log(obj.Name);

But I'm getting the error TypeError: Object is not a function happening on the 'n' of new.

How can I define a class in another file in nodejs? I feel like this should have worked just fine, but it doesn't.

4

1 回答 1

4

你说

module.exports.MyClass = MyClass;

意思是

var MyClass = require('./MyClass').MyClass; // MyClass attached to the exports

如果您希望它在需要时直接可用,您需要做

module.exports = MyClass;
于 2013-05-05T18:09:13.300 回答