call()、apply()和bind()的異同

來源:互聯網
上載者:User

標籤:define   執行   function   pre   his   注意   函數   chrome   func   

相同點:

改變this的指向;

    var a = {        name:"丸子",        fn:function(){            console.log(this.name);        }    }    var b = a.fn;    b()//undefined    b.call(a);//丸子    b.apply(a);//丸子    b.bind(a);//沒有被列印

 

不同點:

1,call和apply都是立即執行,而bind則是返回一個函數;

    var a = {        name:"丸子",        fn:function(){            console.log(this.name);        }    }    var b = a.fn;    b.bind(a)//沒有被列印    var c = b.bind(a)    console.log(c);    //function (){        //console.log(this.name);    //}        c();//丸子

 

2,如果call和apply的第一個參數寫的是null,那麼this指向的是window對象;

    var a = {        name:"丸子",        fn:function(){            console.log(this);            //Window {external: Object, chrome: Object, document: document, a: Object, speechSynthesis: SpeechSynthesis…}        }    }    var b = a.fn;    b()//this指向的是window對象    b.call(null);//this指向的是window對象    b.apply(null);//this指向的是window對象    b.bind(null)//沒有被列印

 

3,參數;

(1),call和apply可以有多個參數,不同的是apply第二個參數必須是一個數組;

    var a = {        name:"丸子",        fn:function(m,n){            console.log(this.name);            console.log(m+n);        }    }    var b = a.fn;    b.call(a,6,6)    // 丸子     // 12    b.apply(a,[6,4]);    // 丸子      // 10

 

(2),同樣bind也可以有多個參數,並且參數可以執行的時候再次添加,但是要注意的是,參數是按照形參的順序進行的。

    var a = {        name:"丸子",        fn:function(m,n){            console.log(this.name);            console.log(m+n);        }    }    var b = a.fn;    b.bind(a)//沒有被列印    var c = b.bind(a,2)    console.log(c);    //function (m,n){        //console.log(this.name);        //console.log(m+n);    //}    c(3);    //丸子    //5

 

call()、apply()和bind()的異同

相關文章

聯繫我們

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