确切地说,这是一种适合功能组成的情况,我正在使用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)");
_.construct
:
new
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
从本质上讲,这是您已经提出的解决方案。