扩展函数原型 [英] Extending the function prototype

查看:36
本文介绍了扩展函数原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在 javascript 中扩展函数原型(也就是说,向所有函数添加一个函数).目的是将其转换为另一种语言之间交换的格式(即ruby,只能通过字符串进行通信[在此特定设置中]).我已经有了一个系统,所以我可以通过在 ruby​​ 对象上定义 to_js 方法和在 javascript 对象上定义 to_ruby 方法来传递其他类型,就像这样

I'm looking to be able to extend the function prototype in javascript (that is to say, add a function to all functions). The purpose is to convert it into a format for exchange between another language (namely ruby, which can only communicate through strings [in this particular setting]). I've already got a system so I can pass around other types by defining a to_js method on ruby objects and a to_ruby method on javascript objects, like so

Number.prototype.to_ruby = function () { return this.toString(); }

这适用于我想要的所有其他内容,但不适用于函数.我可以通过执行以下操作使其在 chrome 中工作:

This is working for everything else I want it to, but not for functions. I can get it to work in chrome by doing the following:

_empty = function() {};
_empty.__proto__.to_ruby = function () {
    return 'JSFunction.new(' + this.toString().to_ruby() + ')';
};

但这在 IE 中不起作用(这是系统的要求).

But this does not work in IE (which is a requirement of the system).

我知道我在某处有一个对象通过 ID 或类似的方式跟踪函数,但我不能保证它们会与创建它们的同一个实例一起使用.

I know I have an object somewhere keeping a track of functions by an ID or similar, but I can't guarantee that they will be used with the same instance that created them.

所有其他失败我只能写一个函数来处理它(即,isFunction(instance) ? fn_to_ruby(instance) : instance.to_ruby(),但我宁愿保留如果可能的话,这个模型.

All else failing I could just write a function to special case deal with it (ie, isFunction(instance) ? fn_to_ruby(instance) : instance.to_ruby(), but I'd rather keep this model if possible.

推荐答案

__proto__ 不是标准属性.试试这个方法:

__proto__ is not a standard property. Try this approach:

(function(){}).constructor.prototype.to_ruby = function(){
    return 'JSFunction.new(' + this.toString().to_ruby() + ')';
};

这篇关于扩展函数原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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