核心代碼
function getCallerArgument() {
var result = [];
var slice = Array.prototype.slice;
var caller = arguments.callee.caller; // 獲取調用者
while (caller) {
result = result.concat(slice.call(caller.arguments, 0)); // 獲取調用者參數
caller = caller.arguments.callee.caller; // 繼續向上追溯
}
return result;
}
// 測試
var a = function() { b('a1', 'a2'); };
var b = function() { c('b1', 'b2'); };
var c = function() { return getCallerArgument(); };
c('c1'); // 返回 ["a1", "a2", "b1", "b2", "c1"]
原理解析
arguments.callee:指向當前正在執行的函數(getCallerArgument)。
callee.caller:指向調用當前函數的函數(即 c)。
caller.arguments:調用者接收到的參數列表(類數組)。
arguments.callee.caller:再上一層調用者(b),以此遞歸向上。
Array.prototype.slice.call(arguments, 0):將類數組轉為真數組並合併。
⚠️ 重大警告:嚴格模式禁用
'use strict';
function test() { console.log(arguments.callee); } // TypeError: 'callee' and 'caller' cannot be accessed in strict mode
- ES5 嚴格模式完全禁止
arguments.callee 和 caller。
- 現代框架、模塊化環境默認嚴格模式,**此技術已廢棄不可用**。
- 性能極差:阻礙 JIT 優化、破壞調用棧完整性、導致內存洩漏風險。
現代替代方案
1. 顯式傳遞上下文對象
function logContext(ctx, ...args) { console.log(ctx, args); }
function a() { logContext({fn: 'a'}, 1, 2); }
function b() { logContext({fn: 'b'}, 3, 4); }
2. Error 堆棧追蹤(調試用)
function getStack() {
return new Error().stack.split('\n').slice(1).map(line => line.trim());
}
3. 異步上下文傳遞:AsyncLocalStorage (Node.js) / Zone.js
const { AsyncLocalStorage } = require('async_hooks');
const store = new AsyncLocalStorage();
function runWithContext(ctx, fn) { store.enterWith(ctx); fn(); }
function getContext() { return store.getStore(); }
4. 參數裝飾器(TypeScript/提案階段)
function Log(target, key, descriptor) {
const fn = descriptor.value;
descriptor.value = function(...args) {
console.log(`${key} called with`, args);
return fn.apply(this, args);
};
}