JavaScript的綁定方法bind

bind語法

fun.bind(this,arg1,arg2,…)
JavaScript函數調用bind方法會返回一個新的方法,新方法的this會綁定傳入對象。

bind應用實例

創建綁定函數

a = 1;
var module = {
    a : 2,
    getA : function () {
        return this.a;
    }
}
console.log(module.getA()); //2
var windowfun = module.getA;
var modulefun = windowfun.bind(module);
console.log(windowfun()); //1
console.log(modulefun()); //2

如上代碼,我們在module中定義了一個方法返回a值,顯然我們直接調用module.getA()將返回module的局部變量a。但是我們將module的getA方法取出來賦給windowfun,此時windowfun的this將指向全局,故調用windowfun得到是全局變量a,值爲1。
現在我們調用windowfun的綁定函數bind,並傳入參數module,返回一個新函數賦給modulefun,那麼此時modulefun的this綁定了module,自然得到的就是局部變量a,爲2。

設置函數預設參數

function list() {
    return Array.prototype.slice.call(arguments);
}
console.log(list(1,2,3));           //[1,2,3]
var list1 = list.bind(undefined,4); //[4]
console.log(list1(1,2,3));          //[4,1,2,3]

首先說一下這個Array.prototype.slice.call這個函數,這個函數的作用是將類數組轉換成真正的數組。對於有length屬性的非數組對象是沒有slice方法的,因此上述代碼在Array的原型上調用slice的call方法相當於調用了”list.slice()”

var ls = {length:2, 0:'first', 1:'second'};
console.log(Array.prototype.slice.call(ls));
//[ 'first', 'second' ]

它的效果就大概這樣子。
bind()函數的第一個參數是this所要綁定的對象,那麼接下來的參數就是要傳入新返回方法的預設參數,我們傳入4,則不再傳入參數直接調用返回就是[4],傳入點其他參數呢就是[4,1,2,3]

setTimeout函數

function Fun1() {
    this.name = 1;
}
Fun1.prototype.fun2 = function () {
    setTimeout(this.fun3,1000);             //name:undefined
    setTimeout(this.fun3.bind(this),1000);  //name:1
}
Fun1.prototype.fun3 = function () {
    console.log('name: '+ this.name);
}
var fun = new Fun1();
fun.fun2();

默認情況下,調用setTimeout函數時this是指向全局的,因此第一個setTimeout將輸出的是undefined,因爲name在全局沒有定義。只要將this.fun3綁定到當前對象,輸出纔是對象的局部變量name,值爲1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章