每次我实例化一个 Error 对象时,都有一个 .stack
字段。假设构建堆栈跟踪是一项代价高昂的操作,我的自然 react 是保留它们用于特殊情况。
不过我记得读过,在 v8 中,堆栈跟踪仅在读取 .stack
字段时计算。
如果我从不读取堆栈,我可以假设 new Error(...)
和 new Object(...)
一样昂贵吗?
这是 JS 引擎的特性还是标准行为?
最佳答案
Error.prototype.stack
是非标准功能,因此其行为取决于实现。
对于基于 V8 的平台,wiki在 GitHub 上说:
The stack trace is collected when the error is created and is the same regardless of where or how many times the error is thrown.
还有 document Node.js 也说了同样的话:
Error objects capture a "stack trace" detailing the point in the code at which the Error was instantiated, and may provide a text description of the error.
因此当 Error
对象被创建时它已经被收集。
但是,直到第一次访问 stack
属性时,它才格式化,如同一维基页面上的段落所述:
For efficiency stack traces are not formatted when they are captured but on demand, the first time the stack property is accessed.
关于javascript - Error 对象的堆栈是什么时候产生的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45541554/