将约束器作为参数,好像它是JavaScript中的常规函数吗? 我正在使用antlr 4,根据antlr 4 javaScript目标的文档,将类实例化并立即将其作为下一类构造函数的参数传递是很常见的: 导入antlr4 ...

问题描述 投票:0回答:1

确切地说,这是一种适合功能组成的情况,我正在使用lodash(fp)。

首先,我尝试了以下内容:
// imports...
import _ from "lodash/fp.js";

const parse = _.compose([
  _.invoke("MyQuery"),
  MyGrammarParser,
  antlr4.CommonTokenStream,
  MyGrammarLexer,
  antlr4.InputStream,
]);

但这失败了。

插入

TypeError: Class constructor ke cannot be invoked without 'new'
new

(除

_.compose
)内部的每一行上都失败了。 INSTEAD,我可以使用辅助功能:

_.invoke

this this working,IMO看起来比原始的好,但是我想知道是否有一种使用内置的JavaScript或Lodash功能编写此功能的方法。据我所知,不可能将构造函数作为一个参数传递,就好像它是常规函数一样,因此
TypeError: Cannot read properties of undefined (reading 'length')
.
总而言之,我想将构造函数作为参数传递,就好像它是常规函数一样,而不必首先将其包装在辅助函数中。
对于那些不熟悉lodash的人,请参阅
仓库
和lodash fpguide
,但是解决这个问题的解决方案应是lodash/antlr 4独立。
    

可以在不使用

new antlr4.InputStream

的情况下调用构造函数:

// imports... import _ from "lodash/fp.js"; _.construct = Constructor => param => new Constructor(param); const parse = _.compose([ _.invoke("MyQuery"), _.construct(MyGrammarParser), _.construct(antlr4.CommonTokenStream), _.construct(MyGrammarLexer), _.construct(antlr4.InputStream), ]); const tree = parse("field = 123 AND items in (1,2,3)");

javascript constructor lodash antlr4 higher-order-functions
1个回答
0
投票
要仅使用香草JS使这个点免费,有

_.construct

new
lodash提供了可以与占位持有人一起使用的lodash,可以更方便:

Reflect.construct
class Example { hello = "world" } //pass an empty array for the constructor arguments const obj = Reflect.construct(Example, []); console.log( obj instanceof Example ); console.log( obj.hello );

,我个人觉得这不是真的值得这样做。最后,它最终会在一个简单函数足够的任务上抛出更多的库代码:
Function#bind

从本质上讲,这是您已经提出的解决方案。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.