JS中的bind方法研究

EcmaScript5給Function擴展了一個方法:bindapp

衆所周知 在jQuery和prototype.js之類的框架裏都有個bind框架

jQuery裏的用途是給元素綁定事件dom

$("#scroll").bind("click",{foo,"bar"}, function() {});//官方API示例bind(type,data,fn)

 

在EcmaScript5中也擴展了叫bind的方法(IE6,7,8不支持),使用方法以下函數

function T(c) {
    this.id = "Object";
    this.dom = document.getElementById("scroll");
}
T.prototype = {
    init: function() {
       //①
        this.dom.onmouseover = function() {
            console.log("Over-->"+this.id);
        }
       //②
        this.dom.onmouseout = function() {
            console.log("Out -->"+this.id);
        } .bind(this)
    }
};
(new T()).init();

 

結果:this

經過①和②的對照加上顯示的結果就會看出bind的做用:改變了上下文的thisurl

 

bindcall很類似,,例如,可接受的參數都分爲兩部分,且第一個參數都是做爲執行時函數上下文中的this的對象。prototype

不一樣點有兩個:code

①bind的返回值是函數xml

//都是將obj做爲上下文的this
function func(name,id) {
    console.log(name,id,this);
}
var obj = "Look here";
//什麼也不加
func("    ","-->");

//使用bind是 返回改變上下文this後的函數
var a = func.bind(obj, "bind", "-->");
a();
//使用call是 改變上下文this並執行函數
var b = func.call(obj, "call", "-->");

結果:對象

②後面的參數的使用也有區別

function f(a,b,c){
    console.log(a,b,c);
}

var f_Extend = f.bind(null,"extend_A")
f("A","B","C")  //這裏會輸出--> A B C

f_Extend("A","B","C")  //這裏會輸出--> extend_A A B

f_Extend("B","C")  //這裏會輸出--> extend_A B C

f.call(null,"extend_A") //這裏會輸出--> extend_A undefined undefined

這個區別不是很好理解

call 是 把第二個及之後的參數做爲f方法的實參傳進去

而bind 雖然說也是獲取第二個及之後的參數用於以後方法的執行,可是f_Extend中傳入的實參則是在bind中傳入參數的基礎上日後排的。

//這句代碼至關於如下的操做
var f_Extend = f.bind(null,"extend_A")

//↓↓↓

var f_Extend = function(b,c){
    return f.call(null,"extend_A",b,c);
}

舉一個應用場景:例如如今有一個方法 根據不一樣的文件類型進行相應的處理,經過bind 就能夠建立出簡化版的處理方法

function FileDealFunc(type,url,callback){
    if(type=="txt"){...}
    else if(type=="xml"){...}
    .....
}

var TxtDealFunc = FileDealFunc.bind(this,"txt");

//這樣使用的時候更方便一些
FileDealFunc("txt",XXURL,func);  //原來
TxtDealFunc(XXURL,func); //如今

 


如下是兼容處理

if (!Function.prototype.bind) {
    Function.prototype.bind = function(obj) {
        var _self = this
            ,args = arguments;
        return function() {
            _self.apply(obj, Array.prototype.slice.call(args, 1));
        }
    }
}
相關文章
相關標籤/搜索