JavaScript ES6 - 错误:导出类时,只能在导出时使用装饰器

Ham*_* L. 4 javascript ecmascript-6 ionic2 angular

我试图在ES6中导出一个函数,所以我可以导入它并在其他文件中使用它来获得DRY代码.

但是我收到以下错误:

在解析文件时导出类(16:0)时,只能在导出时使用装饰器:

@idempotent
export function totalItems() {
    this.cart.items.forEach((dish) => total += item.qty);
    return total;
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

小智 7

你不想支持你要做的事情.该装饰建议(其中尚不规范)仅包括类的定义和他们的方法,而不是函数定义@decorators.

您可能想要创建一个函数装饰器/包装器函数来代替:

export const totalItems = idempotent(function() {
    let total;
    this.cart.items.forEach((dish) => total += item.qty);
    return total;
});
Run Code Online (Sandbox Code Playgroud)


Har*_*eja 2

如果你想导出一个函数,那么你必须像这样添加到特定的类中:

export class GeneralFunctions
{
     totalItems() {
         this.cart.items.forEach((dish) => total += item.qty);
         return total;
     }
}
Run Code Online (Sandbox Code Playgroud)

在您想要使用该函数的地方,只需导入该类并创建它的一个对象,然后使用该对象调用该函数,如下所示:

import {GeneralFunctions} from "./<your-file>";

var obj : GeneralFunctions 
obj.totalItems();
Run Code Online (Sandbox Code Playgroud)