本文介绍了如何使用任意原型创建一个可调用的JS对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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 expect o to have a meaningful prototype. 这篇关于如何使用任意原型创建一个可调用的JS对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-28 04:48