2012-01-18 142 views
1

作爲跟進問題how-to-determine-source-information-of-callback-in-v8,我有以下問題。將sourceLocation屬性添加到函數中?

如果我看一個函數的屬性,我會看到它有一個名稱,一個長度等等。是否可以通過黑客的'函數'對象的構造函數自動添加屬性到所有函數?如果是這樣,應該怎麼做?我想添加一個名爲'source_location'的屬性

function foo() { 
} 

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

但'console.log'顯示源位置了嗎? – c69 2012-01-18 13:03:35

+0

是嗎?你能給個例子嗎? – coen 2012-01-18 13:58:33

+0

[Chrome](http://gyazo.com/69282b23aa0e4fe96958a7120e9bd644.png),[Opera](http://gyazo.com/d47e3e0848b613349ead9ece61278428.png),與Firefox和IE9相同。 – c69 2012-01-18 14:28:03

回答

0

您可以使用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