caller attribute
Returns a reference to the function, that is, the function body that called the current function.
functionName.caller: The functionName object is the name of the executed function.
Note:
For functions, the caller attribute is only defined when the function is executed. If the function is called from the top level of a JScript program, then caller contains null . If the caller attribute is used in a string context, the result is the same as functionName.toString, that is, the decompiled text of the function is displayed.
Js code:
function CallLevel(){ if (CallLevel.caller == null) alert("CallLevel was called from the top level."); else alert("CallLevel was called by another function:\n"+CallLevel.caller); } function funCaller(){ CallLevel(); } CallLevel(); funCaller()
callee attribute
Returns the Function object being executed, which is the body of the specified Function object.
[function.]arguments.callee: The optional function parameter is the name of the Function object currently being executed.
Description:
The initial value of the callee attribute is the Function object being executed.
The callee attribute is a member of the arguments object. It represents a reference to the function object itself, which is helpful for hiding the recursion of the
function or ensuring the encapsulation of the function. For example, the following example recursively calculates the natural numbers from 1 to n. and. This attribute
is only available when the relevant function is executing. It should also be noted that callee has a length attribute, which is sometimes
used for verification. arguments.length is the actual parameter length, and arguments.callee.length is the
formal parameter length. From this, you can determine whether the formal parameter length is consistent with the actual parameter length when calling.
Js code:
//callee可以打印其本身 function calleeDemo() { alert(arguments.callee); } //用于验证参数 function calleeLengthDemo(arg1, arg2) { if (arguments.length==arguments.callee.length) { window.alert("验证形参和实参长度正确!"); return; } else { alert("实参长度:" +arguments.length); alert("形参长度: " +arguments.callee.length); } } //递归计算 var sum = function(n){ if (n <= 0) return 1; else return n +arguments.callee(n - 1) }
The above is the detailed content of Detailed explanation of usage examples of caller attribute and callee attribute of javascript function. For more information, please follow other related articles on the PHP Chinese website!