使用 require/new 在 node.js 中实例化一个新对象
Use require/new to instantiate a new object in node.js
我在使用 node.js 时遇到了非常简单的初学者问题,但我似乎无法使其正常工作。
我想要的只是能够在 index.js 文件中使用 'new' 运算符创建对象。
出于演示目的,我在 Person.js 文件(与我的 index.js 位于同一目录中)中创建了一个简单的 Person
对象,如下所示:
class Person {
constructor() {
this._name = 'bob';
}
set name(name) {
this._name = name
}
get name() {
return this._name;
}
}
现在我想做这样的事情(在 index.js 文件中):
var p = require('./Person.js')
var bob = new p.Person()
我收到的错误消息告诉我 Person 不是构造函数:
var bob = new p.Person()
^
TypeError: p.Person is not a constructor
at Object.<anonymous> (/home/.../index.js:59:11)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
非常感谢任何帮助。
如果你想从另一个 JS 文件中要求或导入 class/function/object/anything,你需要在当前文件中导出它和 import/require。这些被称为模块。
在您的情况下,您需要在创建后导出 Person
class。否则 JS 没有任何引用。添加
module.exports = Person
低于 Person
class。现在你可以实例化
const Person = require('./person');
const p = new Person();
对于新的 ES6 classes,您也可以使用 import/export
。
// Export Person Class
export default class Person {
....
}
// Now, import
import Person from './person'
我在使用 node.js 时遇到了非常简单的初学者问题,但我似乎无法使其正常工作。
我想要的只是能够在 index.js 文件中使用 'new' 运算符创建对象。
出于演示目的,我在 Person.js 文件(与我的 index.js 位于同一目录中)中创建了一个简单的 Person
对象,如下所示:
class Person {
constructor() {
this._name = 'bob';
}
set name(name) {
this._name = name
}
get name() {
return this._name;
}
}
现在我想做这样的事情(在 index.js 文件中):
var p = require('./Person.js')
var bob = new p.Person()
我收到的错误消息告诉我 Person 不是构造函数:
var bob = new p.Person()
^
TypeError: p.Person is not a constructor
at Object.<anonymous> (/home/.../index.js:59:11)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
非常感谢任何帮助。
如果你想从另一个 JS 文件中要求或导入 class/function/object/anything,你需要在当前文件中导出它和 import/require。这些被称为模块。
在您的情况下,您需要在创建后导出 Person
class。否则 JS 没有任何引用。添加
module.exports = Person
低于 Person
class。现在你可以实例化
const Person = require('./person');
const p = new Person();
对于新的 ES6 classes,您也可以使用 import/export
。
// Export Person Class
export default class Person {
....
}
// Now, import
import Person from './person'