zoukankan      html  css  js  c++  java
  • JS中的bind方法学习

    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作为上下文的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));
            }
        }
    }
     
  • 相关阅读:
    用wamp配置的环境,想用CMD连接mysql怎么连
    Mysql删除表
    MySQL创建表
    Leetcode 130. Surrounded Regions
    Leetcode 111. Minimum Depth of Binary Tree
    Leetcode 110. Balanced Binary Tree
    Leetcode 98. Validate Binary Search Tree
    Leetcode 99. Recover Binary Search Tree
    Leetcode 108. Convert Sorted Array to Binary Search Tree
    Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
  • 原文地址:https://www.cnblogs.com/douglasvegas/p/4807263.html
Copyright © 2011-2022 走看看