MathGladiator
MathGladiator

Reputation: 1211

JavaScript, v8, and function printing

In node.js (or v8/chrome), can I rely on using string concatenation for getting the code behind a function?

for instance, in node.js

var f = function(x) { return x; }
console.log(f);

shows "[Function]" while

console.log("" + f);

shows "function(x) { return x;}"

is this a reliable semantic? Is this in the ECMA spec somewhere?

Upvotes: 2

Views: 1517

Answers (2)

Erik Corry
Erik Corry

Reputation: 650

In the case of V8 what the implementation specific code will do is to return the source of the function as passed into the engine. V8 doesn't have a byte code so it doesn't disassemble the byte code to reconstruct the function source. It just keeps the source around in case it is ever asked to do toString() on a function.

Upvotes: 1

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827742

Well, I would say yes, since you are using V8.

What the String contatenation is really doing behind the scenes, is to invoke the Function.prototype.toString method, for example:

var str = "" + f;

Is roughly equivalent to:

var str = f.toString();

This method provides an implementation-dependent string representation of the function, it can vary between implementations, for example whitespace, or optimizations can me done.

But since you are targeting an specific implementations I think you won't have any problem.

If you are getting "[object Function]" it's because (oddly) the Object.prototype.toString is being executed instead the Function.prototype.toString one, e.g.:

Object.prototype.toString.call(function () {}); // "[object Function]"

Upvotes: 2

Related Questions