1. 程式人生 > >JS中的bind()方法

JS中的bind()方法

Function.prototype.bind()方法

bind()方法主要就是將函式繫結到某個物件,bind()會建立一個函式,函式體內的this物件的值會被繫結到傳入bind()第一個引數的值,例如,f.bind(obj),實際上可以理解為obj.f(),這時,f函式體內的this自然指向的是obj

例子

var a = {
    b : function(){
        var func = function(){
            console.log(this.c);
        }
        func();
    },
    c : 'Hello!'
}
a.b();
//undefined
注意:這裡的this指向的是全域性作用域,所以會返回undefined
var a = {
    b : function(){
        var that = this;
        var func = function(){
            console.log(that.c);
        }
        func();
    },
    c : 'Hello!'
}
a.b();
//Hello!
注意:可以通過賦值的方式將this賦值給that
var a = {
    b : function(){
        var func = function(){
            console.log(this.c);
        }.bind(this);
        func();
    },
    c : 'Hello!'
}
a.b();
//Hello!
 
var a = {
    b : function(){
        var func = function(){
            console.log(this.c);
        }
        func.bind(this)();
    },
    c : 'Hello!'
}
a.b();
//Hello!
注意:當然,也可以通過bind的方式繫結this,上述兩種bind繫結的方式都可以
再看另外一種用法

例子

function f(y, z){
    return this.x + y + z;
}
var m = f.bind({x : 1}, 2);
console.log(m(3));
//6
注意:這裡bind方法會把它的第一個實參繫結給f函式體內的this,所以這裡的this即指向{x : 1}物件,從第二個引數起,會依次傳遞給原始函式,這裡的第二個引數2,即是f函式的y引數,最後呼叫m(3)的時候,這裡的3便是最後一個引數z了,所以執行結果為1 + 2 + 3 = 6
分步處理引數的過程其實是一個典型的函式柯里化的過程(Curry)

我們再來看一道題目

var a = document.write;
a('hello');
//Error
 
a.bind(document)('hello');
//hello
 
a.call(document, 'hello');
//hello
注意:這裡直接呼叫a的話,this指向的是global或window物件,所以會報錯,通過bind或者call的方式繫結this至document物件,即可正常呼叫
可以用bind的方式預定義引數,例子

function list(){
    return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3);
//[1, 2, 3]
 
//預定義引數
var a = list.bind(undefined, 10);
 
var list2 = a();
//[10]
 
var list3 = a(1, 2, 3);
//[10, 1, 2, 3]
注意:這裡的Array.prototype.slice.call(arguments)是用來將引數由類陣列轉換為真正的陣列,a的第一個引數undefined表示this的指向,第二個引數10即表示list中真正的第一個引數,依次類推


如何自己實現bind方法?

因為bind()函式釋出在ES5中,因此並不能很好的在所有瀏覽器中執行,需要Polyfill,當然現在幾乎所有現代瀏覽器都支援ES5

//my_bind方法支援繫結物件
Function.prototype.my_bind = function(context){
    var self = this;
    return function(){
        return self.apply(context, arguments);
    }
}
 
//測試
function a(){
    return this.name;
}
a();    //''
 
var b = {name : 'kong'};
a.bind(b)();    //kong
 
a.my_bind(b)();        //kong
上述是最簡單的一種實現方式,僅可用來繫結,不可傳參
更加健壯的方式:

//my_bind方法不僅可以繫結物件,還可以傳參
Function.prototype.my_bind = function(context){
    var args = Array.prototype.slice.call(arguments, 1);
    //args [7, 8]
    var self = this;
    return function(){
        var innerArgs = Array.prototype.slice.call(arguments);
        //innerArgs [9]
        var finalArgs = args.concat(innerArgs);
        //finalArgs [7, 8, 9]
        return self.apply(context, finalArgs);
    }
}
 
//測試
function a(m, n, o){
    return this.name + ' ' + m + ' ' + n + ' ' + o;
}
 
var b = {name : 'kong'};
 
a.my_bind(b, 7, 8)(9);        //kong 7 8 9
注意:這裡my_bind函式中args表示的是在bind時傳入的預定義引數,這裡即為7和8,分別表示m和n,return中的innerArgs表示的是呼叫a的時候傳入的引數,這裡表示9,即o,最後用concat連線兩個陣列,即為finalArgs,所以最後執行的是a(7, 8, 9),this指向b,實現了一個完善點的bind方法

處理bind返回的函式如果作為建構函式,搭配new關鍵字出現的話,我們繫結的this就需要被忽略的相容性問題

更加完美的方式

//bind返回的函式如果作為建構函式,搭配new關鍵字出現的話,我們繫結的this就需要被忽略
//處理建構函式場景下的相容
Function.prototype.bind = Function.prototype.bind || function(context){
    //確保呼叫bind方法的一定要是一個函式
    if(typeof this !== "function"){
        throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }
    var args = Array.prototype.slice.call(arguments, 1);
    var self = this;
    var F = function(){};
    F.prototype = this.prototype;
    var bound = function(){
        var innerArgs = Array.prototype.slice.call(arguments);
        var finalArgs = args.concat(innerArgs);
        return self.apply(this instanceof F ? this : context || this, finalArgs);
    }
    bound.prototype = new F();
    return bound;

--------------------- 
作者:kongjunchao159 
來源:CSDN 
原文:https://blog.csdn.net/kongjunchao159/article/details/59113129 
版權宣告:本文為博主原創文章,轉載請附上博文連結!