如何使用任意原型制作可调用的 JS 对象? [英] How do I make a callable JS object with an arbitrary prototype?

查看:20
本文介绍了如何使用任意原型制作可调用的 JS 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
JavaScript 对象是否可以具有原型链,也可以是一个函数?

我希望制作一个可调用的 JavaScript 对象,具有任意原型链,但不修改 Function.prototype.

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);

不进行任何全局更改.

推荐答案

没有什么可以阻止您向函数添加任意属性,例如.

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.

这是通过将对象 o 注入原型链来实现的,但是有几点需要注意:

This works by injecting the object o into the prototype chain, however there are a few things to note:

  • 我不知道 IE 是否支持 __proto__,或者甚至有一个等效的,从一些评论来看,这看起来只适用于基于 Firefox 和 safari 的浏览器(所以 camino、chrome 等也可以使用).
  • o.__proto__ = f.__proto__; 只对 function.toString 这样的函数原型函数才是真正必要的,所以你可能想跳过它,特别是如果你期望 o要有一个有意义的原型.
  • 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 expect o to have a meaningful prototype.

这篇关于如何使用任意原型制作可调用的 JS 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆