【发布时间】:2020-05-26 06:05:45
【问题描述】:
我正在尝试运行下面的代码,但它不起作用。我认为这是一个范围问题,但我不确定如何解决。
import CommonController from './CommonController';
import CategoryService from './category/Service.js';
class CategoryController extends CommonController {
constructor() {
super(CategoryService);
}
}
export default new CategoryController();
// ===================CommonController==========================
export default class CommonController {
constructor(service) {
this.service = service;
}
async get () {
console.log(this); // it returns undefined
}
}
// ===================CategoryService==========================
import Category from './Category'
import dto from './dto'
class CategoryService extends CommonService {
constructor() {
super(Category, dto);
}
}
export default new CategoryService();
// ===================CommonService==========================
export default class CommonService {
constructor(model, dto) {
this.model = model;
this.dto = dto;
}
}
如果运行:
import CategoryController from './CategoryController';
CategoryController.get()
CommonController get 函数中的 console.log 会打印 undefined
我做错了吗?
【问题讨论】:
-
您的
this在async get ()的上下文中,可能未定义。您是否查看过关于如何注入this的 babel 文档? -
我无法重现,在调用
categoryController.get()中this关键字指的是categoryController。 -
“我做错了什么吗?” - 不要default-export
newclass instances。要么导出整个类,要么只使用一个对象字面量(甚至use named exports) -
async get service() {return await this.service}
标签: javascript class undefined babeljs extends