如何使用任意原型创建一个可调用的JS对象? [英] How do I make a callable JS object with an arbitrary prototype?
问题描述
可能重复:
一个JavaScript对象是否可以有一个原型链,但也可以是一个函数?
< blockquote>
我正在寻找一个带有任意原型链的可调用JavaScript对象,但没有修改Function.prototype。
换句话说,这是必须的:
var o = {x:5 };
var foo = bar(o);
assert(foo()===Hello World!);
删除foo.x;
assert(foo.x === 5);
不进行全局更改
解决方案没有什么能够阻止你将任意属性添加到函数中,例如:
函数bar(o){
var f = function(){returnHello World!; }
o .__ proto__ = f .__ proto__;
f .__ proto__ = o;
返回f;
}
var o = {x:5};
var foo = bar(o);
assert(foo()===Hello World!);
删除foo.x;
assert(foo.x === 5);
我相信应该做你想做的。
这是通过将对象
o
注入到原型链中来实现的,但需要注意以下几点:
- 我不知道IE是否支持
只有真正必要的__ proto __
,或者甚至有一个等价的,frome一些评论,看起来只适用于firefox和safari (如camino,chrome等)也是如此。
o .__ proto__ = f .__ proto __;
对于像function.toString这样的函数原型函数,您可能只想跳过它,特别是如果您期望o
具有有意义的原型。
Possible Duplicate:
Can a JavaScript object have a prototype chain, but also be a function?I'm looking to make a callable JavaScript object, with an arbitrary prototype chain, but without modifying Function.prototype.
In other words, this has to work:
var o = { x: 5 }; var foo = bar(o); assert(foo() === "Hello World!"); delete foo.x; assert(foo.x === 5);
Without making any globally changes.
解决方案There's nothing to stop you from adding arbitrary properties to a function, eg.
function bar(o) { var f = function() { return "Hello World!"; } o.__proto__ = f.__proto__; f.__proto__ = o; return f; } var o = { x: 5 }; var foo = bar(o); assert(foo() === "Hello World!"); delete foo.x; assert(foo.x === 5);
I believe that should do what you want.
This works by injecting the object
o
into the prototype chain, however there are a few things to note:
- I don't know if IE supports
__proto__
, or even has an equivalent, frome some's comments this looks to only work in firefox and safari based browsers (so camino, chrome, etc work as well).o.__proto__ = f.__proto__;
is only really necessary for function prototype functions like function.toString, so you might want to just skip it, especially if you expecto
to have a meaningful prototype.这篇关于如何使用任意原型创建一个可调用的JS对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!