【问题标题】:Trying to call a static method from an imported ES6 module尝试从导入的 ES6 模块调用静态方法
【发布时间】:2018-04-15 16:22:32
【问题描述】:

我正在使用 Firefox 56,并将 dom.moduleScripts.enabled 设置为 true。这让我可以使用原生 ES6 模块。

我有一个 vue2 组件,它定义了一个方法:

import StorageZonesAjaxMethods from '../../ajax/storage-zones.js';
....
methods: {
        updateList() 
        {
            //console.log(StorageZonesAjaxMethods);
            StorageZonesAjaxMethods.getList();//function(response) { this.list = response.data.payload;});

        },
    },

具有方法的类在哪里:

export default new class StorageZonesAjaxMethods {

    static getItem(id, then)
    {
        axios.get(`${Config.apiBaseUrl}/storage-zones/${id}`)
            .then(response => then);
    }

    static getList(then)
    {
        alert('in get list');
        axios.get(`${Config.apiBaseUrl}/storage-zones`)
            .then(response => then);
    }

我在 firefx 中收到错误 "TypeError: (intermediate value).getList is not a function",但 console.log 显示它是,但由于某种原因它在构造函数中。怎么回事?

【问题讨论】:

    标签: javascript module ecmascript-6 vue.js


    【解决方案1】:

    Never use new class { … }!

    还有don't default-export a class with only static methods。简化为

    export default {
        getItem(id) {
            return axios.get(`${Config.apiBaseUrl}/storage-zones/${id}`);
        }
        getList() {
            alert('in get list');
            return axios.get(`${Config.apiBaseUrl}/storage-zones`);
        }
    };
    

    或者甚至更好地更改两个文件并使用

    export function getItem(id) {
        return axios.get(`${Config.apiBaseUrl}/storage-zones/${id}`);
    }
    export function getList() {
        alert('in get list');
        return axios.get(`${Config.apiBaseUrl}/storage-zones`);
    }
    

    import * as StorageZonesAjaxMethods from '../../ajax/storage-zones.js';
    

    【讨论】:

    • 我来自真正的编码世界。一类静态方法是没有代码味道的!我考虑过只导出对象,但我更愿意在语义上进行分组,因为你知道,这就是类的用途。
    • @user3791372 我不知道你所说的“真正的编码世界”是什么意思,但在 JS 中它绝对是一种代码味道。使用类来组织代码是一种 Java 技术。 JS 有模块和对象作为一等公民。
    【解决方案2】:

    经验教训 - 不要用疲倦的眼睛编码。课堂上的export default new class StorageZonesAjaxMethods 不应该有new 那里

    【讨论】:

      猜你喜欢
      • 2019-06-05
      • 1970-01-01
      • 2019-03-27
      • 2016-04-23
      • 2021-02-03
      相关资源
      最近更新 更多