面试题答案
一键面试1. caller
属性的用途
caller
属性返回一个对调用当前函数的函数的引用。例如,如果函数B
调用了函数A
,那么在函数A
内部,A.caller
将引用函数B
。这在调试或实现特定的控制流逻辑时可能有用,比如跟踪函数调用栈。
2. 不支持或存在兼容性风险的JavaScript环境
- ES5及更新版本:在严格模式下,函数的
caller
属性是不可访问的,访问它会抛出一个类型错误(TypeError
)。在非严格模式下,虽然有些环境可能支持,但这已经是不推荐使用的特性,未来可能会被移除。 - 现代JavaScript运行时:例如Node.js v14+和最新的浏览器环境,都遵循ES规范,在严格模式下禁止访问
caller
属性,即使在非严格模式下,也不鼓励使用,因为它不符合现代JavaScript的设计理念。
3. 替代方案
方案一:使用函数参数传递上下文
function outerFunction() {
const context = {
name: 'outer'
};
innerFunction(context);
}
function innerFunction(callerContext) {
console.log(`Called by function with context: ${callerContext.name}`);
}
outerFunction();
方案二:使用错误对象的栈信息(适用于调试场景)
function outerFunction() {
try {
throw new Error();
} catch (e) {
const stack = e.stack;
const callerFunctionName = stack.split('\n')[2].match(/at\s+(.*?)\s+\(/)[1];
console.log(`Caller function name: ${callerFunctionName}`);
}
innerFunction();
}
function innerFunction() {
console.log('Inner function');
}
outerFunction();