call和apply的簡單介紹

來源:互聯網
上載者:User

標籤:

call,apply基本一樣,不同就是參數的傳遞

<!doctype html><html lang="en"><head><meta charset="UTF-8"><title></title><script>window.onload=function () {    function fn1 (a,b)     {        console.log(this);        console.log(a+b);    }        fn1.call(this,1,2);}</script></head><body></body></html>

得到的結果是,document,3,不信你在chrome、FF下開啟看看
call能乾的事,apply也能幹,不過形式有點不同

fn1.apply(this,[1,2]);

apply第二個參數是以數組形式展現的,

下面用一個更典型的例子來說明apply用法

我們在在一堆數組中找一個最大的數,一般我們是這樣乾的

var arr=[3,55,99,3,62,83,17];    console.log( Math.max(3,55,99,3,62,83,17) );

結果顯示是99。

但是當這個數組很長很長,或者是還不是很確定裡面的個數時,我們該怎麼去判斷裡面最大的值呢?這是apply出場了,

console.log( Math.max.apply(null,arr) );

前面的那個null可以不管,把這個數組塞進去就可以了,這樣一樣得到結果99。

 

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.