【问题标题】:JavaScript es6 call static function from another classJavaScript es6 从另一个类调用静态函数
【发布时间】:2016-07-02 07:52:02
【问题描述】:

这是带有静态函数的类

import alt from '../alt';
import Parse from 'parse';
import { ElementTypes } from '../constants/ElementTypes';

class BoardActions {

    static getDefaultElement(x, y) {
        var Element = Parse.Object.extend("Element");
        var element = new Element();
        element.set("x", x);
        element.set("y", y);
        return element;
    }
}

export default alt.createActions(BoardActions);

而这是调用静态函数const startElement = BoardActions.getDefaultElement(0, 3);的类

import alt from '../alt';
import Parse from 'parse';
import { ElementTypes } from '../constants/ElementTypes';
import BoardActions from './BoardActions';

class ProjectActions {

    createNewProject(name) {
        return (dispatch) => {
            dispatch();
            const Project = Parse.Object.extend("Project");
            const project = new Project();
            let projectObject = null;
            project.set('name', name);
            project.save().then((object) => {
                projectObject = object;
                const startElement = BoardActions.getDefaultElement(0, 3);
                startElement.set('type', ElementTypes.StartType);
                startElement.set('root', true);
                startElement.set('projectId', object.id);
                return startElement.save();
            }).then((object) => {
                this.newProjectCreated(projectObject);
            }, (error) => {
                this.parseError(error);
            });
        }
    }

}

export default alt.createActions(ProjectActions);

我收到此错误:

ProjectActions.js:69 Uncaught TypeError: _BoardActions2.default.getDefaultElement is not a function

怎么了?

编辑: 我使用 babel 作为转译器。

"babel-core": "^6.5.1",
"babel-loader": "^6.2.2",
"babel-preset-es2015": "^6.5.0",
"babel-preset-react": "^6.5.0",
"babel-preset-react-hmre": "^1.1.0",
"babel-preset-survivejs-kanban": "^0.3.3",

【问题讨论】:

  • 在您的代码中找不到任何问题。你用的是哪个编译器?
  • 我正在使用 babel 作为编译器
  • 这些类是否在不同的文件中?如果是这样,您可能应该显示您正在导出/导入的内容。
  • 我添加了这些导入
  • 什么是alt.createActions

标签: javascript parse-platform ecmascript-6 static-methods alt.js


【解决方案1】:

已编辑(因为您编辑了问题):

在您要导入的第二个文件中

import BoardActions from './BoardActions';

从 './BoardActions' 导入默认值。

查看第一个文件,您正在导出函数的结果而不是类本身。

export default alt.createActions(BoardActions);

【讨论】:

  • 他的模块已经有一个默认导出。 (诚​​然,它只是在编辑中添加的)
  • 谢谢。相应地编辑了我的答案
  • 谢谢。导出默认 alt.createActions(BoardActions);使所有功能基本上是静态的。我刚刚从函数中删除了 static 并且它起作用了。
  • @zeiteisen:“使所有功能基本上是静态的”???这听起来像是实例化了该类以从中创建一个单例。你真的不应该那样做。相反,只需删除对createActions的调用!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 2017-05-18
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
相关资源
最近更新 更多