Chr*_*ann 5 javascript prototype function
我正在使用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"
Run Code Online (Sandbox Code Playgroud)
我可以创建增强我的所有功能与功能double成员,但我会记得每一个我创建了一个时间打电话给它Hey,Sayonara等功能.此外,我的问候语函数将直接在函数对象上为每个实例提供所有这些成员.我宁愿将它们全部放在一个原型中,并将其作为我所有问候语功能的原型.以下选项也不起作用:
hello.__proto__(非标准,不适用于所有浏览器)Function.prototype直接(将这些成员添加到所有其它功能,但它们没有任何意义那里-我只是想打电话给double一组我自己的函数)甚至可以给函数对象一个自定义原型,还是我坚持修改我创建的每个函数对象?
更新:我将上面的示例更改为更类似于我正在处理的实际问题.这是关于modyfing 函数对象而不是普通对象.最终目标是为解析器组合器提供舒适的语法,例如(非常简化):
//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(…))
Run Code Online (Sandbox Code Playgroud)
我希望能够将成员添加到一组函数中,这样,当调用这些成员时,它们会根据调用它们的函数返回新函数.这将用于解析器组合器/ monadic解析器.
小智 4
是的,您可以,使用setPrototypeOf.
function prototype() { }
prototype.double = function() { console.log("double"); };
function myfunc() { }
Object.setPrototypeOf(myfunc, prototype);
myfunc.double();
Run Code Online (Sandbox Code Playgroud)
这本质上是 的标准化版本__proto__。
除了 Function.prototype 之外,没有其他方法可以直接创建带有原型的函数。考虑:
function makeFunc() {
return function x() { };
}
function protofunc { }
protofunc.double = { }...
makeFunc.prototype = protofunc;
new makeFunc()
Run Code Online (Sandbox Code Playgroud)
不幸的是,通过从构造函数返回一个函数makeFunc而不是默认值this,makeFunc.prototype不会应用 。
或者:
myFunc = Object.create(protofunc, ???);
Run Code Online (Sandbox Code Playgroud)
通常我们会想到使用Object.create原型来创建一个对象,但在这种情况下,没有办法指定一个函数作为对象。
底线:唯一的选择是显式设置原型,您可以使用__proto__、 或 来执行此操作setPrototypeOf。这是 ES6 的一个特性。普通浏览器支持警告适用。请参阅http://kangax.github.io/compat-table/es6/。