我試圖創建一個類,FriendlyStack
,用於包含消息和堆棧跟蹤的調試。我主要用它來檢測競爭條件。當console.dir
叫我的類的實例,我想根節點的文字顯示信息。在JavaScript中,覆蓋console.dir(myObj)的根文本
我的功能名稱是gotHere()
,它在FriendlyStack
的實例上調用console.dir
。
// debugging helper function
function gotHere(msg) {
console.dir(new FriendlyStack(msg));
}
class FriendlyStack {
constructor(msg) {
this.msg = msg;
// new Error().stack gets the string of the stack trace
// .split('\n') creates an array of each line of the stack trace
// .slice(3) removes the first three lines, which are:
// Error
// at new FriendlyStack (...)
// at gotHere (...)
this.stack = new Error().stack.split('\n').slice(3);
}
// some override to make console.dir display this.msg as the root node
// instead of FriendlyStack
}
對於大多數類/對象,當你調用console.dir
顯示的樹的根是對象的原型的名字。
console.dir({foo: 'bar'})
v Object
foo: "bar"
> __proto__: Object
console.dir([1, 2, 3])
v Array[3]
0: 1
1: 2
2: 3
length: 3
> __proto__: Array[0]
但是,當您在字符串或數字上調用它時,顯示的根就是該值。
console.dir(1)
> 1
console.dir('foobar')
> foobar
我本來期望,給調用console.dir(someObject)
,那console.dir(1)
會顯示Number
作爲根節點的行爲。這種不同的行爲表明可能有方法來改變打印爲根節點的內容,但也可能只是基元是特殊情況。
有沒有辦法達到我期望的行爲?我試圖超載FriendlyStack.toString
,但那沒有奏效。
難道是準確的詞組你想要的行爲爲「有控制檯。 dir()顯示記錄數據的原始數據類型? –
@ barry-johnson我不確定。我希望控制檯顯示「console.dir」所做的交互式樹形結構,以便在展開根節點時看到堆棧數組。我不確定'console.log'是否有這種行爲。 – dfoverdx
我更新了我的評論,'console.log'是一個肌肉記憶錯誤。 –