《javascript進階程式設計》——參考型別之Function

來源:互聯網
上載者:User
1.函數實際上是對象,函數名實際上是一個指向函數對象的指標。
function sum(num1,num2){    return num1+num2;}alert(sum(10,10));//20var anotherSum=sum;alert(anotherSum(10,10));//20sum=null;alert(anotherSum(10,10));//20

因此沒有重載,同名函數,後者會覆蓋前者。 2.函式宣告和函數運算式

//正常運行alert(sum(10,10));function sum(num1,num2){    return num1+num2;}//出現錯誤alert(sum(10,10));var sum=function(num1,num2){    return num1+num2;};
3.作為值的函數

可以從一個函數中返回另一個函數,例如下面這個例子:

function compare(propertyName){    return function(obj1,obj2){        var value1=obj1[propertyName];        var value2=obj2[propertyName];        return value2-value1;    };}
4.函數內部屬性

函數內部有兩個特殊的對象:arguments和this。arguments包含著傳入函數的所有參數,它有一個callee的屬性,這是一個指標,指向擁有該arguments對象的函數。

function fac(num){    if(num<=1)        return 1;    else        return num*fac(num-1);}

上述是個典型的求階乘函數,在其函數內部用到了函數名,這會增加執行與名字的耦合度,因此可以像下面這樣:

function fac(num){    if(num<=1)        return 1;    else        return num*arguments.callee(num-1);}var anotherFac=fac;alert(anotherFac(5));//120fac=function(){    return 0;}alert(anotherFac(5));//120


this引用的是函資料以執行的環境對象。

window.color="red";function sayColor(){    alert(this.color);}var o={    color:"blue"}sayColor();//redo.sayColor=sayColor;o.sayColor();//blue

還有一個屬性:caller。它儲存著調用當前函數的函數的引用。

strict 模式下不能用arguments.callee和arguments.caller。

5.函數方法

有兩個方法:call()和apply()。用途都是在特定的範圍中運行函數。apply接受兩個參數:一個是運行函數的範圍,另一個是參數數組。

function sum(num1,num2){    return num1+num2;}function sum2(num1,num2){    return sum.apply(this,[num1,num2]);}function sum3(num1,num2){    return sum.apply(this,arguments);}alert(sum2(10,10));//20alert(sum3(10,10));//20

call()的區別在於其參數必須逐個列舉出來。

function sum4(num1,num2){    return sum.apply(this,num1,num2);}alert(sum4(10,10));//20

上述兩個方法的強大之處在於其能夠擴大函數賴以啟動並執行範圍。

window.color="red";var o={color:"blue"};function sayColor(){    alert(this.color);}sayColor();//redsayColor.apply(this);//redsayColor.apply(o);//blue     

顯然這樣擴充範圍的好處是,對象不需要與方法有任何耦合關係。

函數繼承的toString()和toLocaleString()以及valueOf()會返回函數的代碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.