函數對象的內部方法call(), apply(), bind()

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   sp   on   div   

這三個函數都是指向函數本身的,call()和apply()的第一參數都是這個函數要執行的內容物件,之後的參數是這個函數執行要傳的參數,不同的地方時call是以枚舉的方式傳參,apply是以數組的形式傳參,當然也可以傳遞arguments對象。bind()是把該函數綁定到指定的context上下文執行環境中,簡單講就是把該函數的this對象指向傳到bind()中的參數context上,並返回一個函數執行個體。

簡單的寫個範例程式碼我們就可以瞭然了:

<script>    function sayHi(name,greeting){        var name = name||this.name,        greeting = greeting||this.greeting;        console.log("Hello "+name+","+greeting);    }         var name = "Terry",    greeting = "how are you?",    me = {name:"John",    greeting:"你好!"};        sayHi.call(this,name,greeting);    sayHi.call(this);    sayHi.apply(this,[name,greeting]);        sayHi.apply(me,[me.name,me.greeting]);    sayHi.call(me,me.name,me.greeting);    //bind()會返回函數執行個體,後面加()直接執行    sayHi.bind()();    sayHi.bind(me)();    </script>

 

 

 執行結果:

函數對象的內部方法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.