提到bind方法,估計你們還會想到call方法、apply方法;它們都是Function對象內建的方法,它們的第一個參數都是用來更改調用方法中this的指向。須要注意的是bind
是返回新的函數,以便稍後調用;apply
、call
則是當即調用原函數 。而今天咱們主要講解bind方法的理解與使用。數組
bind方法是EcmaScript5新增的方法,該方法在mdn上是這麼介紹的:app
bind()方法建立一個新的函數(稱爲綁定函數), 當被調用時,將其this關鍵字設置爲提供的值,在調用新函數時,在任何提供以前提供一個給定的參數序列。函數
語法:this
fun.bind(thisArg[, arg1[, arg2[, ...]]])
參數thisArg表示:當綁定函數被調用時,該參數會做爲this的指向。當使用new
操做符調用綁定函數時,該參數無效。spa
參數arg1, arg2, ...表示:
當綁定函數被調用時,這些參數將置於實參以前傳遞給被綁定的方法。prototype
先來看個例子:code
this.name="jack"; var demo={ name:"rose", getName:function(){return this.name;} } console.log(demo.getName());//輸出rose 這裏的this指向demo
var another=demo.getName; console.log(another())//輸出jack 這裏的this指向全局對象 //運用bind方法更改this指向 var another2=another.bind(demo); console.log(another2());//輸出rose 這裏this指向了demo對象了
bind的應用對象
能夠對一個函數預設初始參數:blog
function a(){ return Array.prototype.slice.call(arguments);//將類數組轉換成真正的數組 } var b=a.bind(this,15,20) alert(b());//彈出 15,20 var s=b(25,30); alert(s);//彈出 15,20,25,30