1

Example:

function f(a){ return a }
var g = f.bind(null);
g.toString() // chrome:  function () { [native code] }
             // firefox: function bound f() { [native code] }

Is there some subtle reason why g.toString() is not returning the original source code?

Of course, I could easily "fix" that by overriding Function.prototype.bind but my question is: am I doing something stupid like opening some security hole with this?

var o_bind = Function.prototype.bind;
Function.prototype.bind = function(){
        var f = o_bind.apply(this, arguments);
        f.orig_func = this;
        return f;
}
function fsrc(f){
        return f.orig_func ?
                String(f.orig_func).replace(/^function/, '$& bound') :
                String(f);
}
6
  • 4
    Well, .bind returns a new function. Commented Nov 6, 2016 at 16:30
  • @FelixKling, you are correct, but f.toString() != g.toString() :) (the bind probably returns a native function that when called does the actual call to the original function with the relevant thisArg) Commented Nov 6, 2016 at 16:37
  • @Dekel indeed, that is what it does. A simplified version of bind is to just return the following function() { return f.apply(thisArg, arguments); }. A full version is not that much different but would handle the partial allocation functionality. Commented Nov 6, 2016 at 16:51
  • @Dekel: "but f.toString() != g.toString()" Exactly. I usually don't expect two different functions to have the same source. Especially not a native vs a user defined function. Commented Nov 6, 2016 at 16:51
  • The same thing could be said about closures -- they're always a different function though sharing the same "code": function f() { return function(){ } } f()==f() // false f().toString()==f().toString() // true What bothers me is the possibility that there may be some programming patterns that /rely/ on a bind() not leaking any info about the original into the new function. Commented Nov 6, 2016 at 17:27

1 Answer 1

2

The spec says about Function.protoype.toString (emphasis mine):

If func is a Bound Function exotic object, then
Return an implementation-dependent String source code representation of func. The representation must conform to the rules below. It is implementation dependent whether the representation includes bound function information or information about the target function.

In other words, environments are free to include the source of the original function or not.


am I doing something stupid like opening some security hole with this?

Given that toString returns a function's source code for "normal" user defined functions, probably not.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.