javascript方法--bind()

來源:互聯網
上載者:User

標籤:ons   一個   bind   app   win   cti   javascrip   全域   使用   

bind方法,顧名思義,就是綁定的意思,到底是怎麼綁定然後怎麼用呢,下面就來說說我對這個方法的理解。

 

文法

fun.bind(this,arg1,arg2,...)

bind()方法會建立一個新的函數,稱為綁定函數,fun方法在this環境下調用

該方法可傳入兩個參數,第一個參數作為this,第二個及以後的參數則作為函數的參數調用

 

執行個體 

1.建立綁定函數

 

this.a = 1;
var module = {
a : 2,
getA:function() {
return this.a;
}
};
module.getA();//2

var getA1 = module.getA;
// getA在外部調用,此時的this指向了全域對象
getA1();//1

// 再把getA1方法綁定到module環境上
var getA2 = getA1.bind(module);
getA2();

按 Ctrl+C 複製代碼按 Ctrl+C 複製代碼

 

從上面的例子可以看出,為什麼要建立綁定函數,就是當我們調用某些函數的時候是要在特定環境下才能調用到,所以我們就要把函數放在特定環境下,就是使用bind把函數綁定到特定的所需的環境下。

 

 

2.讓函數擁有預設的參數

使用bind()方法使函數擁有預設的初始參數,這些參數會排在最前面,傳給綁定函數的參數會跟在它們後面

 

 1 function list(){ 2     // 讓類數組arguments擁有數組的方法slice,這個函數實現了簡單把類數群組轉換成數組 3     return Array.prototype.slice.call(arguments); 4 } 5  6 list(1,2,3);//[1,2,3] 7  8 //給list綁定一個預設參數4  9 var list1 = list.bind(undefined,4);10 11 list1();//[4]12 13 list1(1,2,3);//[4,1,2,3]

 

 

3.setTimeout的使用

正常情況下,調用setTimeout的時候this會指向全域對象,但是使用類的方法時我們需要指向類的執行個體,所以要把this,綁定要回呼函數方便繼續使用執行個體

 1 function Fun1() {  2   this.name = 1; 3  } 4 Fun1.prototype.fun2 = function() { 5   window.setTimeout(this.fun3.bind(this), 1000); 6  } 7 Fun1.prototype.fun3 = function(){ 8     console.log(‘name:‘+this.name);//name:1 9 }10 var fun = new Fun1();11 fun.fun2();

 

4.快捷方法--把類數群組轉換成數組

第一種方法是使用apply方法

1 function fun1() {2     var slice = Array.prototype.slice;3     return slice.apply(arguments);4 }5 6 fun1(1,2,3);//[1,2,3]

 

第二種方法是使用call方法和bind方法一起使用

function fun2() {    var unboundSlice = Array.prototype.slice;    // 把函數的call方法綁定在數組slice方法上,之後再給call方法傳遞參數    var slice = Function.prototype.call.bind(unboundSlice);    return slice(arguments);}fun2(1,2,3);//[1,2,3]

javascript方法--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.