我正在尝试运行以下代码,但无法正常工作。我认为这是一个范围问题,但是我不确定如何解决。
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中的console.log get函数将打印未定义
我做错什么了吗?
问题是您要在类本身上调用get()
,而不是在类的实例上调用它。尝试创建CategoryController
的实例,如下所示:
cc = new CategoryController();
然后,您应该可以拨打电话:
cc.get();
下面代码中的演示(与您的演示相同,只是稍作修改以反映我的观点)。
// ===================CommonController==========================
class CommonController {
constructor(service) {
this.service = service;
}
async get () {
console.log(this); // it returns undefined
}
}
// ===================CommonService==========================
class CommonService {
constructor(model, dto) {
this.model = model;
this.dto = dto;
}
}
// ===================CategoryService==========================
class CategoryService extends CommonService {
constructor() {
super(Category, dto);
}
}
class CategoryController extends CommonController {
constructor() {
super(CategoryService);
}
}
cs = new CategoryController();
cs.get();