如何从子模块访问父方法
How to access parent methods from submodule?
我有以下模块/类和子模块设置
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
对象上的自己的模块)。
相关文章:
- 如何从对象的原型方法访问JavaScript对象属性
- 从vuejs中的组件模板访问父方法
- 访问对象的最简单方法'的单独财产
- 有没有一种方法可以从光滑的网格访问插件
- 尝试访问方法的 OOP JavaScript
- 从匿名函数层内访问方法变量
- jQuery控件之外的访问方法
- 访问方法内部的变量's函数
- Angular2:模板中类的访问方法
- 在javascript中使用对象访问方法
- 如何在原型继承模式中访问方法
- async模块内部类的访问方法或
- 当用作其他对象的事件处理程序时,访问方法中的成员
- 在javascript中访问方法skillet.toString()
- 为什么我的applet在通过JavaScript访问方法时不能加载本地库?
- 另一个插件的访问方法
- 使用jquery脚本时如何访问方法
- Javascript -如何在没有'this'的情况下改变作用域和访问方法?
- 为什么我的主干模型奇怪地嵌套在集合中,需要钻取才能访问方法/属性?
- Javascript OOP -从原型设置器访问方法