首頁  >  文章  >  web前端  >  js arguments,jcallee caller用法總結

js arguments,jcallee caller用法總結

高洛峰
高洛峰原創
2017-01-04 17:21:591185瀏覽

關鍵字:arguments,callee,caller
arguments:表示傳入函數的參數
callee:表示函數和函數主體的語句
caller:表示呼叫函數的函數

arguments

呼叫它的函數的參數。

caller

傳回一個對函數的引用,該函數呼叫了當前函數。
functionName.caller
functionName 物件是所執行函數的名稱。

說明
對於函數來說,caller屬性只有在函數執行時才有定義。如果函數是由頂層呼叫的,那麼 caller包含的就是 null 。如果在字串上下文中使用 caller 屬性,那麼結果和functionName.toString一樣,也就是說,顯示的是函數的反編譯文字。

callee

傳回正被執行的 Function 對象,也就是所指定的Function 對象的正文。

[function.]arguments.callee

可選項 function 參數是目前正在執行的 Function 物件的名稱。

說明

callee 屬性的初始值就是正被執行的 Function 物件。

callee 屬性是 arguments物件的一個成員,它表示對函數物件本身的引用,這有利於匿名函數的遞歸或保證函數的封裝性,例如下邊範例的遞歸計算1到n的自然數之和。而該屬性僅當相關函數正在執行時才可用。還有要注意的是callee擁有length屬性,這個屬性有時候用來驗證還是比較好的。 arguments.length是實參長度,arguments.callee.length是形參長度,由此可以判斷調用時形參長度是否和實參長度一致。

<script type=&#39;text/javascript&#39;>
function test(x,y,z) 
{ 
alert("实参长度:"+arguments.length);
alert("形参长度:"+arguments.callee.length);
alert("形参长度:"+test.length);
alert(arguments[ 0 ])         
alert(test[ 0 ])           // undefined 没有这种用法
}
//test(1,2,3); 
test(1,2,3,4);
/*
*  arguments不是数组(Array类)
*/
Array.prototype.selfvalue  =   1 ;
function  testAguments() {
    alert( " arguments.selfvalue= " + arguments.selfvalue);
}
alert("Array.sefvalue="+new Array().selfvalue);
testAguments();
/**/ /*
 * 演示函数的caller属性.
 * 说明:(当前函数).caller:返回一个对函数的引用,该函数调用了当前函数
  */
function  callerDemo()  {
     if  (callerDemo.caller)  {
         var  a =  callerDemo.caller.arguments[ 0 ];
        alert(a);
    }   else   {
        alert( " this is a top function " );
    }
}
function  handleCaller()  {
    callerDemo();
}
 callerDemo();
 handleCaller("参数1","参数2");

/**/ /*
 * 演示函数的callee属性.
 * 说明:arguments.callee:初始值就是正被执行的 Function 对象,用于匿名函数
  */
function  calleeDemo()  {
    alert(arguments.callee);
}
 calleeDemo();
 (function(arg0,arg1){alert("形数数目为:"+arguments.callee.length)})();

/**/ /*
 * 演示apply,call函数的用法
 * 说明:作用都是将函数绑定到另外一个对象上去运行,两者仅在定义参数方式有所区别:
 *       apply(thisArg,argArray);
 *     call(thisArg[,arg1,arg2…] ]);
 *     即所有函数内部的this指针都会被赋值为thisArg
  */
  function  ObjectA() {
    alert( " 执行ObjectA() " );
    alert(arguments[ 0 ]);
     this .hit = function (msg) {alert(msg)}
     this .info = " 我来自ObjectA "
 }

  function  ObjectB() {
    alert( " 执行ObjectB() " );
     // 调用ObjectA()方法,同时ObjectA构造函数中的所有this就会被ObjectB中的this替代
    ObjectA.apply( this ,arguments); // ObjectA.call(this);
    alert( this .info);
 }
  ObjectB(&#39;参数0&#39;);

  var  value = " global 变量 " ;
  function  Obj() {
     this .value = " 对象! " ;
 }
  function  Fun1() {
    alert( this .value);
 }
   Fun1();
   Fun1.apply(window); 
   Fun1.apply(new Obj());
</script>


更多js arguments,jcallee caller用法總結相關文章請關注PHP中文網!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn