2

I am trying to print an object to the console to see the values using console.log(). I see that functions are printed this way.

variable1:
    title:
        "hello world!!!"
variable2:
callback: ƒ callback()
length: 0
name: "callback"
prototype:
constructor: ƒ callback()
[[Prototype]]: Object
arguments: (...)
caller: (...)
[[FunctionLocation]]: functions_mapper.ts:10

Is there any way to get the exact function definition instead of the location? My use case is not just to output and see but to download it in a file. How can I do this? Thanks!!!

PS: Doing variable2.callback.toString() gives the function definition, but the object has different types of variables in a nested fashion. And we aren't aware of them. When doing copy(object) from the console is giving variable2: {}. How to make it store the function definition? Do we have to go to each nested variable, check if it is a function, and call the toString() method?

Harry
  • 21
  • 2
  • Does this answer your question? [How to get function body text in JavaScript?](https://stackoverflow.com/questions/12227735/how-to-get-function-body-text-in-javascript) – lusc May 15 '22 at 18:39
  • Not sure why you would want to "download" a function into a file? What is your whole use case? – Bergi May 15 '22 at 18:57
  • @Bergi I want to download the object into a file. – Harry May 15 '22 at 19:25
  • @Harry it is not possible to download an object. At best, you can download a serialisation of the object. But again, what do you need the object for? What do you want to do with the file after it has been downloaded? – Bergi May 15 '22 at 19:34

1 Answers1

3

Function.prototype.toString should get you what you want.

Function.prototype.toString.call(function xxx() { return 1; })
> 'function xxx() { return 1; }'

You can just call .toString() on the function -- in other words, callback.toString() in your example -- in 99.99% of cases also, but Function.prototype.toString is more guaranteed to work (conceivably the .toString() of your function could have been replaced with something other than the standard implementation).

David P. Caldwell
  • 3,394
  • 1
  • 19
  • 32