【问题标题】:Add sourceLocation property to a function?将 sourceLocation 属性添加到函数?
【发布时间】:2012-02-13 04:37:26
【问题描述】:

作为问题how-to-determine-source-information-of-callback-in-v8 的后续,我有以下问题。

如果我查看函数的属性,我会发现它有名称、长度等。是否可以通过破解“函数”对象的构造函数来自动为所有函数添加属性?如果是这样,应该怎么做?我想添加一个名为“source_location”的属性

function foo() {
}

console.log(foo.name); //works out of the box
console.log(foo.source_location); //can I make this work?

【问题讨论】:

  • console.log 已经显示源位置?
  • 是吗?能举个例子吗?
  • Chrome , Opera, Firefox 和 IE9 一样。
  • Function.caller 是非标准的,但绝对是 V8 的一部分,因此您应该可以使用。
  • 这不是我提出的问题的解决方案。我想知道一个函数的 source_location 。不是来电者。在我给出的示例中,甚至没有调用者。

标签: javascript node.js constructor prototype v8


【解决方案1】:

您可以使用 v8 的调试器对象。

来源

// test.js

function bar() {
}

function foo() {
}

foo.source_location = debug.Debug.findFunctionSourceLocation(foo);

console.log(foo.name);
console.log(foo.source_location);
console.log(foo.source_location.script.name);

执行

node --expose-debug-as=debug test.js

输出

foo 
{ script: {}, // script object 
  position: 106,
  line: 5,
  column: 12,
  start: 94,
  end: 110 }
/home/skomski/test.js

参考文献

http://code.google.com/p/v8/source/browse/trunk/src/debug-debugger.js#586

【讨论】:

    猜你喜欢
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    相关资源
    最近更新 更多