如何从子模块访问父方法

How to access parent methods from submodule?

本文关键字:访问 方法 模块      更新时间:2023-09-26

我有以下模块/类和子模块设置

MyAPI.js

class MyAPI {
  construction(){
    this.food = require('./Food');
  }
}
module.exports = MyAPI;

Food.js

class Food {
  constructor(){
    ...
  }
}
module.exports = Food;

app.js

var api = require('./MyAPI');
var taco = new api.food;
var cheeseburger = new api.food;

我想知道的是,是否可以在Food.js中调用MyAPI属性和函数形式?我需要以某种方式将this传递到需求中吗?

this.food = require('./Food')(this); // this didn't work...

上述结果是:

TypeError: Class constructors cannot be invoked without 'new'

但是我为什么要在MyAPI构造函数中使用new呢?

这里做子类和子模块并从中创建新对象的最佳方法是什么?

我认为您混淆了类和实例:

var MyAPI = require('./MyAPI');//this is a class
var apiInstance = new MyAPI();//the creates a new instance of your class
var taco = new apiInstance.food //the food property on your api is a class not an instance
var tacoInstance = new taco();

this.food是在MyApi的构造函数中分配的,因此您需要实例化MyApi才能访问该属性。

var Api = require('./MyAPI');
var apiInstance = new Api();
var foodInstance = new apiInstance.food();

从您的评论来看,您似乎希望MyApi的属性,特别是config的属性可以由子模块访问。除了将您的顶级API对象设为单例之外,我看不出有什么方法可以做到这一点:

var MyAPI =  {
  config: { setting: 'default' },
  Food: require('./Food')
}
module.exports = MyAPI;
var MyApi = require('./my-api.js');
class Food {
  constructor(){
    // MyApi.config
  }
}
module.exports = Food;

从AWS源代码来看,他们正在做类似的事情(除了config是安装在顶级AWS对象上的自己的模块)。