0

If I store a javascript function inside an Object like this :

jsObject = {
  TestFuntion1 : function(){
    var x = 1;
    return x;
  },
  
  TestFunction2 : function(){
    console.log("Hello World");
  }
}

Can I get the content of these function as a string ?

var x = 1; return x;    /*OR*/   console.log("Hello World");

I tried playing with the 'prototype', but nothing seems to return me the content of it. Thank you for your help !

Tryall
  • 640
  • 12
  • 22

1 Answers1

1

This can be done with the toString() function followed by a little parsing to make it look as desired:

function functionToSingleLineString(fn){
    //convert to string
    var str = fn.toString();

    //parse to make it look like you want and return
    return str.substring(0, str.length - 1).replace("function(){", "").trim().replace(/\n/g, "").replace(/\s+/, " ");
}

//check the results
console.log( functionToSingleLineString(jsObject.TestFuntion1) );//STRING: var x = 1; return x;
console.log( functionToSingleLineString(jsObject.TestFuntion2) );//STRING: console.log("Hello World");
Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15
  • This approach is really brittle... I don't see what the point is of getting the body without the enclosing function expression, nor the point of reformatting it to a single line. – Patrick Roberts Dec 01 '19 at 17:46
  • I do as the asker commands. It's not our job to ask why he needs the code. – Aaron Plocharczyk Dec 02 '19 at 00:11
  • Maybe he wants to neatly output short functions into a div on the page. There's nothing wrong with asking for this, and there's nothing wrong with helping him out. – Aaron Plocharczyk Dec 02 '19 at 00:18
  • If we don't question, then who does? The point of comments is to give feedback. This question is most likely [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) and the fact that something this brittle is considered acceptable is really quite alarming. – Patrick Roberts Dec 02 '19 at 00:19
  • The code I provided is good. Whether it is the right approach depends entirely on what he's doing with it. I'll leave you two to talk if he needs more help. – Aaron Plocharczyk Dec 02 '19 at 00:26