標籤:style blog http java color 使用
函數內部的屬性:arguments 和this是函數內部的兩個特殊對象arguments:function recursion(num){ if(num<=1){ return 1; }else{ return num*recursion(num-1); }}另一種寫法:function recursion(num){ if(num<=1){ return 1; }else{ return num*arguments.callee(num-1); }}arguments:表示當前參數的數組arguments.callee 表示引用當前正在正在執行的函數,或者說是調用arguments.callee的函數的引用,arguments.callee給匿名函數提供了一種自我引用的方式var func=function(){ alert(func===arguments.callee);}func();//調用該函數,我們得出的結果是true從該例子我們可以看出func和arguments.callee對象的類型和值都相等。callee屬性的初始值就是正在執行的Function對象caller: 返回一個對函數的引用,該函數調用了當前函數 this 對象: this對象引用的是window(windwo是一個對象,而且是js當中最大的一個對象 ,並且它是最外圍的對象) alert(window);//[object window] alert(typeof window);//object window 是對象 類型是對象 表示全域 alert(this); // [object Window] this 目前表示的是window,因為在window的範圍下 alert(typeof this);//object alert(this===window);//傳回值為 true 在“全域”變數下的this 就是window window.color=‘紅色的‘; function sayColor(){ //alert(this);// [object window] alert(this.color);//因為該函數 sayColor() 未賦值給一個對象 所以此處的this依然代表著window對象 } sayColor();// 調用的是window下的color var box={ color:‘藍色的‘ }; box.sayColor=sayColor;將sayColor函數賦值給了 box對象的sayColor屬性 /* 上邊的代碼其實就相當於 var box={ color:‘藍色的‘, sayColor:function(){ //alert(this);// [object Object] alert(this.color); } }; */ box.sayColor();//此處執行的是box裡邊的this.color //結果是 藍色的 --------------------------------------------<script type="text/javascript">function box(num1,num2){ return num1+num2;}//可以使用這種方式將sum函數轉換成 box方法function sum(num1,num2){ return box.apply(this,[num1,num2]);//此處的this指的是window對象(將this換成window也是一樣的),數組表示的是傳遞的參數}alert(sum(19,21));//返回的結果是40->函數apply: 文法:apply[[thisObj],[argArray]] 定義:應用某一個對象的一個方法,用一個對象替換當前對象 thisObj代表某一個對象 上述例子中這個對象是當前對象 this argArray表示用來替換當前對象的的對象的參數 數組上述例子的另一個中寫法function sum2(num1,num2){ return box.apply(this,arguments);//arguments代表的是box函數中參數的數組}alert(sum2(10,10)); ->使用apply和call可以冒充另一個方法 apply與call實現的效果是一樣的 call和apply不同的是 call中的參數是一個一個的,而apply則必須以數組的形式傳遞function sum(num1,num2){ return box.call(this,num1,num2);//注意參數的傳遞方式和apply的不同之處} alert(sum(10,10)); 冒充的作用:主要用於擴充函數賴以啟動並執行範圍 /* var color=‘紅色‘; var box={ color:‘藍色‘ }; function sayColor(){ alert(this.color); } //使用call 冒充 window對象 sayColor.call(window);//紅色 彈出的是window對象的 color sayColor.call(this);// 紅色 彈出的樣式window對象的color //使用call 冒充 box對象 sayColor.call(box);//藍色 彈出的是 box對象下的color屬性 */ 此時 可以看出 並沒有給box對象添加 sayColor屬性對象卻可以執行出 sayColor的效果View Code