【问题标题】:TypeError: _this2.function is not a function类型错误:_this2.function 不是函数
【发布时间】:2018-02-14 21:31:18
【问题描述】:

我有一个小图书馆,里面的课程很少。在其中一个类中,我使用其他类的方法,因此我实例化它们,并在代码中使用它。

我使用的一些类引用方法带有this 关键字。

示例:

// index.js
import Class1 from './class1'
import Class2 from './class2'
import Class3 from './class3'

export {
   Class1,
   Class2,
   Class3
}

// class1.js
export default Class1 {
   func1() {
      return 'something';
   }

  func2() {
      return this.func1() + 'else';
  }

}

// class2.js
export default Class2 {
   func1() {
      return 'something';
   }

  func2() {
      return this.func1() + 'else again';
  }

}

// class3.js

import {Class1, Class2} from './index';
const c1 = new Class1();
const c2 = new Class2();

export default Class3 {
   funcNotWorking(){
       return c1.func2() + c2.func3() + 'this does not work'
   }

}

我只是通过导入来在测试中使用它:

// test.js
const c3 = require('library.js').Class3

// test stuff calling:
c3.funcNotWorking()

我正在使用 webpack 和 babel loader 编译它。这个配置似乎在编译时工作,其他一切工作,但是这个......

我读到人们似乎在使用 React 时遇到了麻烦,但这只是 Es6。有人可以指点我如何解决这个问题吗?

【问题讨论】:

  • 在class3.js文件中导出默认的Class2,你确定这是你想要的吗?
  • @ŁukaszKapica 你是对的。错别字,但这是一个解释问题的例子
  • 为什么不创建一个新的 Class3 实例,就像使用 Class1 和 Class2 一样?
  • @ŁukaszKapica 因为在我的真实代码中,第 3 类是一个由其他类的方法组成的类...在某些地方我需要第 2 类的一些格式化日期、其他对 html 的降价等为了简化我的生活,我为常见的工作流程做了 Class3。 (我正在迁移一些 es5 代码。)我更正了另一个错字
  • 这很酷,但 funcNotWorking 是一个实例方法,你使用它就像是一个静态方法

标签: javascript ecmascript-6 es6-class es6-modules


【解决方案1】:

上下文在我的代码中丢失了。

我在出现问题的代码中使用了递归、映射和箭头函数。 Babel 编译版本_this2 没有跟上上下文。

我提取了一些方法,在类构造函数中分配它们并在类中使用提取的方法并正确编译。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 2016-02-26
    • 2013-04-01
    • 2016-03-06
    • 2017-02-24
    • 1970-01-01
    相关资源
    最近更新 更多