开发者

JavaScript, v8, and function printing

开发者 https://www.devze.com 2023-01-22 04:00 出处:网络
In node.js (or v8/chrome), can I rely on using string concatenation for getting the code behind a function?

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.l开发者_Python百科og(f);

shows "[Function]" while

console.log("" + f);

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

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


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]"


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号