Flo*_*erl 4 javascript oop require node.js
我在使用 node.js 时遇到了非常简单的初学者问题,但我似乎无法让它正常工作。
我想要的只是能够使用 index.js 文件中的“new”运算符创建对象。出于演示目的,我Person在 Person.js 文件(与我的 index.js 位于同一目录)中创建了一个简单的对象,如下所示:
class Person {
constructor() {
this._name = 'bob';
}
set name(name) {
this._name = name
}
get name() {
return this._name;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想做这样的事情(在 index.js 文件中):
var p = require('./Person.js')
var bob = new p.Person()
Run Code Online (Sandbox Code Playgroud)
我收到的错误消息告诉我 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
Run Code Online (Sandbox Code Playgroud)
任何帮助是极大的赞赏。
如果你想从另一个 JS 文件中要求或导入类/函数/对象/任何东西,你需要在当前文件中导出和导入/要求它。这些被称为模块。
在您的情况下,您需要Person在创建后导出类。否则 JS 没有任何对它的引用。添加
module.exports = Person
Run Code Online (Sandbox Code Playgroud)
在Person班级之下。现在你可以实例化
const Person = require('./person);
const p = new Person();
Run Code Online (Sandbox Code Playgroud)
对于新的 ES6 类,您也可以使用import/export。
// Export Person Class
export default class Person {
....
}
// Now, import
import Person from './person'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5066 次 |
| 最近记录: |