JS中的bind方法学习

来源:互联网 发布:全篇翻译软件 编辑:程序博客网 时间:2024/06/07 16:07

EcmaScript5给Function扩展了一个方法:bind

众所周知 在jQuery和prototype.js之类的框架里都有个bind

jQuery里的用途是给元素绑定事件

$("#scroll").bind("click", function() {});

 

在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();

 

结果:


通过①和②的对照加上显示的结果就会看出bind的作用:改变了上下文的this

 

bindcall很相似,,例如,可接受的参数都分为两部分,且第一个参数都是作为执行时函数上下文中的this的对象。

不同点有两个:

①bind的返回值是函数

//都是将obj作为上下文的thisfunction 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 Cf_Extend("A","B","C")  //这里会输出--> extend_A A Bf_Extend("B","C")  //这里会输出--> extend_A B Cf.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));        }    }}

 

1 0
原创粉丝点击