JavaScript中Call()以及Apply()的應用

來源:互聯網
上載者:User

標籤:

apply()和call()的真正用武之地是能夠擴充函數賴以啟動並執行範圍

三點說明:

1、每個函數都包含兩個非繼承而來的方法:apply()和call()。

2、他們的用途相同,都是在特定的範圍中調用函數。

3、接收參數方面不同,apply()接收兩個參數,一個是函數啟動並執行範圍(this),另一個是參數數組。
   call()方法第一個參數與apply()方法相同,但傳遞給函數的參數必須列舉出來。

使用執行個體:

第一個執行個體:

        function print(a, b, c, d) {            alert(a + b + c + d);        }        function example(a, b , c , d){             //用call方式借用print,參數顯式打散傳遞             print.call(this, a, b, c, d);             //用apply方式借用print, 參數作為一個數組傳遞,             //這裡直接用JavaScript方法內本身有的arguments數組             print.apply(this, arguments);             //或者封裝成數組             print.apply(this, [a, b, c, d]);             }        //下面將顯示”背光指令碼”        example("背","光","腳","本");     
View Code

第二個執行個體:

        function Animal(name)        {            this.name = name;            this.showName = function () {                alert(this.name);            }        }        function Cat(name)        {            Animal.call(this, name);        }                var cat = new Cat("Black Cat");        cat.showName();    
        function Animal(name)        {            this.name = name;            this.showName = function () {                alert(this.name);            }        }        function Cat(name)        {            Animal.call(this, name);        }        Cat.prototype = new Animal();                var cat = new Cat("Black Cat");        cat.showName();        alert(cat instanceof Animal);

 

JavaScript中Call()以及Apply()的應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.