2

So, I'm looking for toSourceString() method for Function object which will return the source code of the Function object in String format.

For example, If I have

(function(a, b) { 
  function useThis(c,d) { 
    return 'hello' + c + d; 
  } 
  console.log(useThis('Jenny', 'Jim')); 
}).bind(this);

kind of function, then I wish if I run toSourceString(), I will just get the inner source part of the function like:

function useThis(c,d) { 
   return 'hello' + c + d; 
} 
console.log(useThis('Jenny', 'Jim'));

Is there any default function that works across browsers? Or is there any Regex way to find some string and replace/remove the first and the end?

5
  • 1
    Function.prototype.toString, have you checked it? Commented Sep 22, 2014 at 9:57
  • @raina77ow That returns the entire thing, not just the inside. Commented Sep 22, 2014 at 9:59
  • 1
    Of course, but it's rather trivial to extract the body, don't you think? ) My point is, have the OP investigated the docs before asking, he probably wouldn't have asked at all. Commented Sep 22, 2014 at 10:00
  • On the second thought, it seems the question is not about toString - but on how to extract the original function after bind. Would be great to have a clarification - is bind in the question intentional, or not. Commented Sep 22, 2014 at 10:02
  • 1
    If the question is indeed about 'bind-reversing', I don't believe it's possible. See, Function.prototype.bind actually creates a new function, that invokes the 'original' one with a set context (one can check _.bind source, for example, to study the approach). The point is, the new function is basically a compiled one - that's why its toSource shows just [native code] or something similar. Commented Sep 22, 2014 at 10:12

1 Answer 1

1

Try this:

myFunction.toString().replace(/^function[^{]+{/,'').slice(0,-1)

Gets the function, strips the beginning and end.

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.