【发布时间】:2011-07-05 08:29:30
【问题描述】:
我正在开发 JavaScript 中的解析器组合器库。为此,我想创建可以像任何其他函数一样调用的函数,但也有可以依次调用的成员函数,以根据它们所附加的函数(例如组合器)产生输出。
我当然可以将成员添加到这样的函数中:
//the functions I want to add additional members to
function hello(x) {
return "Hello " + x;
}
function goodbye(x) {
return "Goodbye " + x;
}
//The function I want as a member of the above functions.
//it creates another function based on the function it is
//attached to.
function double() {
var that = this;
return function(x) {
return that(x) + ", " + that(x);
};
}
//I can attach them manually to the function objects:
hello.double = double;
//calling hello.double()('Joe') results in => "Hello Joe, Hello Joe"
goodbye.double = double;
//calling goodbye.double()('Joe') results in => "Goodbye Joe, Goodbye Joe"
我可以创建一个函数,用 double 成员扩充我的所有函数,但我必须记住每次创建 Hey、Sayonara 等函数时都要调用它。此外,我的问候函数将具有所有这些成员,每个成员都直接位于函数对象上,用于每个实例。我更愿意将它们全部放在一个原型中,并将其作为我所有问候功能的原型。以下选项也不起作用:
- 替换
hello.__proto__(非标准,不适用于所有浏览器) - 直接修改
Function.prototype(也会将这些成员添加到所有其他函数中,但它们在那里没有意义 - 我只想在我自己的一组函数上调用double)
是否可以为函数对象提供自定义原型,或者我是否坚持修改我创建的每个函数对象?
更新:我将上面的示例更改为更类似于我正在处理的实际问题。这是关于修改 函数对象 不是普通对象。最终目标是为解析器组合器启用舒适的语法,例如(非常简化):
//parses one argument
var arg = …
//parses one function name
var name = …
//parses a function call, e.g. foo(x+y, "test", a*2)
var functionCall = name.then(elem("(")).then(arg.repSep(",")).then(")").into(process(…))
我希望能够将成员添加到一组函数,因此,当调用这些成员时,它们会根据调用它们的函数返回新函数。这将用于解析器组合器/单子解析器。
【问题讨论】:
标签: javascript function prototype