首页 > 解决方案 > 如何在 node.js 的当前上下文中嵌入对象?

问题描述

我有一个 node.js 脚本文件。我需要一个具有静态函数的类。我想将类直接嵌入到脚本的当前上下文中,这样我就可以调用类的函数名而不引用类名。

在类文件中:

class SomeClass {
     static doIt() {...}
}

在脚本文件中:

let cls = require('SomeClass');

// **** embed class into current context here ***

// Just call the function without class reference
doIt();

我以前见过这样做。在网上找不到如何做到这一点。

标签: javascriptnode.js

解决方案


您可以使用解构来做到这一点:

class SomeClass {
     static doIt() {...}
     static otherFunc() {...}
}

const { doIt, otherFunc } = SomeClass;

doIt();

推荐阅读