JavaScript 函數對象的 function.caller 屬性返回調用指定函數的函數。如果函數 “f” 被 JavaScript 中的頂級代碼調用,則返回 null。對於像嚴格函數、異步函數和生成器函數這樣的函數,此方法返回 null。
用法:
function.caller
參數:此函數不接受任何參數。
返回值:此函數返回空對於嚴格的異步函數和生成器函數調用者。
為了更好地理解函數方法,下麵給出了幾個例子。
範例1:
HTML
<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, 
        initial-scale=1.0">
</head>
  
<body>
    <script>
  
        // Creating func2
        function func2() {
            console.log("This is from function 2")
        }
        // Creating func1
        function func1() {
            func2();
        }
  
        // Call Function 1
        func1();
  
        // null is returned as function
        // is strict, async function and 
        // generator function
        console.log("from function.caller:", 
                                func1.caller)
    </script>
</body>
  
</html>輸出:

範例2:
HTML
<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
            "width=device-width, 
            initial-scale=1.0">
</head>
  
<body>
    <script>
        function myFunc() {
            if (myFunc.caller == null)
                console.log("The function "
                    + "was called from the top!");
            else
                console.log("This function's "
                    + "caller was " + myFunc.caller);
    }
        myFunc()
    </script>
</body>
  
</html>輸出:

支持的瀏覽器:
- 穀歌瀏覽器
 - 微軟邊
 - 火狐瀏覽器
 - IE瀏覽器
 - Safari
 - Opera
 
相關用法
- Javascript Math.LOG10E用法及代碼示例
 - Javascript Math.LOG2E用法及代碼示例
 - Javascript Math.LN10用法及代碼示例
 - Javascript Math.SQRT1_2用法及代碼示例
 - Javascript Math.PI用法及代碼示例
 - Javascript Math.SQRT2用法及代碼示例
 
注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 JavaScript function.caller Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
