萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 獲取函數調用鏈所有參數:arguments.callee.caller 實戰

核心代碼

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"]

原理解析

  1. arguments.callee:指向當前正在執行的函數(getCallerArgument)。
  2. callee.caller:指向調用當前函數的函數(即 c)。
  3. caller.arguments:調用者接收到的參數列表(類數組)。
  4. arguments.callee.caller:再上一層調用者(b),以此遞歸向上。
  5. 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);
    };
}
copyright © 萬盛學電腦網 all rights reserved