在nodejs中的父/子类层次结构

child.js

class Child { constructor(){ this.helloWorld = "Hello World"; } run() { } } export default new Child(); 

parent.js

 import child from './child.js'; class Parent { constructor() { this.child = child; } } export default new Parent(); 

index.js

 import parent from './parent.js' console.log(parent.child.helloWorld); <-- does not throws an error, displays "Hello World" console.log(parent.child.run); <-- throws an error (Cannot read property run from undefined) console.log(parent.child.run()); <-- throws an error (Cannot read property run from undefined) 

如果我在index.js中做console.log(parent.child),run不会显示出来,但是helloWorld的属性是..

我怎么能暴露的function? 我希望能够做到这一点,以帮助保持我的代码更加有组织,所以将它分离成单独的类,以帮助最大限度地减less每个文件中的代码量。

从一开始就明确一件事情: 你似乎得到的错误与没有出现在console.log输出中的run无关。

如果你的代码真的抛出这个错误,那么这意味着parent.child的值是undefined 。 因此,当你调用console.log(parent.child) ,你应该看到undefined ,而不是一个对象。 但是,我不明白为什么你会得到这个错误。


无论如何, run是在parent.child原型上定义的,而不是在它本身上定义的。 console.log最有可能显示对象自己的属性(控制台API不标准化,因此结果可能因环境而异)。 这很正常

简单的例子来重现:

 var foo = { x: 42 }; var bar = Object.create(foo); bar.y = 21; console.log(bar, bar.x, bar.y); // Open the browser console to see output 

那么我不知道如果可以帮助你解决问题,但是每当我想添加inheritance,我使用extendssuper这里是一个例子:

基类:

 class BaseDataModel { constructor() { } getModel() { return 'model'; } module.exports.BaseDataModel = BaseDataModel; 

类扩展基类:

 "use strict" // Imports const BaseDataModel = require('../baseDataModel').BaseDataModel; // use the proper location class UserMembershipModel extends BaseDataModel { constructor() { super(); // this is optional, I use this to inherit the constructors } getChildModel() { return super.getModel(); // This is how you access the function from your extended class } module.exports.UserMembershipModel = UserMembershipModel; 

再次,不知道是否它解决了你的问题,因为你实际上添加一个属性与儿童类。 我的例子实际上是扩展(或UserMembershipModel从BaseDataModelinheritance)。

希望这可以帮助你一点。