Function prototype extension

I am looking to be able to extend a function prototype in javascript (i.e. add a function to all functions). The goal is to convert it to a format for exchange between another language (namely, a ruby ​​that can only communicate through strings [in this particular setting]). I already have a system, so I can pass other types, defining a method to_jsfor ruby ​​objects and a method to_rubyfor javascript objects, for example

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

This works for everything I want, 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() + ')';
};

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

I know that I have an object somewhere where a function is tracked using an identifier or the like, but I cannot guarantee that they will be used with the same instance that created them.

Otherwise, I could just write a function with a special case with it (i.e. isFunction(instance) ? fn_to_ruby(instance) : instance.to_ruby(), but I would prefer to keep this model, if possible.

+5
source share
3 answers

__proto__not a standard property. Try this approach:

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

As Slace said, you can add this method to all objects by adding it to Object.prototype, but this is not completely kosher, as this can affect poorly written for loops .. in.

You can add it only to functions through Function.prototype:

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

: , , , , (, ECMAScript ). , toRuby:

function toRuby(obj) {
  return obj.toString();
}

+ , toString :

'' + obj; // returns obj.toString()

, . .

+3

__proto__ - JavaScript, pesudo-standard, . IE - , .

JavaScript, Object:

Object.prototype.foo = function () { console.log('foo'); };
(1).foo();
'asd'.foo();
(true).foo();
({ bar: 'baz' }).foo();
-1

All Articles