【问题标题】:'this' returns undefined in extended Classes in Javascript'this' 在 Javascript 的扩展类中返回未定义
【发布时间】: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

我做错了吗?

【问题讨论】:

  • 您的thisasync get () 的上下文中,可能未定义。您是否查看过关于如何注入 thisbabel 文档?
  • 我无法重现,在调用categoryController.get()this 关键字指的是categoryController
  • 我做错了什么吗?” - 不要default-export new class instances。要么导出整个类,要么只使用一个对象字面量(甚至use named exports
  • async get service() {return await this.service}

标签: javascript class undefined babeljs extends


【解决方案1】:

问题是您在类本身上调用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();

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 2011-04-30
    • 2018-01-15
    • 2012-05-21
    • 1970-01-01
    相关资源
    最近更新 更多