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));
        }
    }
}
相关文章
相关标签/搜索