zoukankan      html  css  js  c++  java
  • bind() 理解 【转】

    bind()可稍后执行  call()  apply()

    为了搞清这个陌生又熟悉的bind,google一下,发现javascript1.8.5版本中原生实现了此方法,目前IE9+,ff4+,chrome7+支持此方法,opera和safari不支持(MDN上的说明)。 
    bind的作用和apply,call类似都是改变函数的execute context,也就是 runtime 时 this 关键字的指向。但是使用方法略有不同。一个函数进行bind后可稍后执行。

     bind 方法实现:绑定this  和 “科里化”:

    function getConfig(colors,size,otherOptions){

      console.log(colors,size,otherOptions)

    }

    var defaultConfig = getConfig.bind(null,"#f00","1024*768");

    defaultConfig("123");  //#f00 1024*768 123

    defaultConfig("345");  //#f00 1024*768 345

    因为bind 方法是EMS5 以后提出的方法,对于老的浏览器,可以使用手写一个bind 方法

    if(!Function.prototype.bind){

      Function.prototype.bind = function(oThis){

        if(typeOf this !== 'function'){

          throw new TypeError('What is trying to be bound is not callable')

        }

        var aArgs = Array.prototype.slice.call(arguments,1),

          fToBind = this,

          fNOP = function(){};

          fBound = function(){

            return fToBind.apply(this instanceof fNOP?this:oThis,

               aArgs.concat(Array.prototype.slice.call(arguments)))

          }

        fNOP.prototype = this.prototype;

        fBound.prototype = new fNOP();

        return fBound;

      }

    }

  • 相关阅读:
    Java单例模式
    svn 清理失败 (clean up 失败) 的解决方法
    linux chrome 安装过程记录
    docker
    linux-cat-grep
    linux-批量结束进程
    linux-压缩与解压缩(gz,zip,tar,jar,war)
    git-服务器地址切换
    linux-tomcat连接数查询
    git-无法add文件的问题
  • 原文地址:https://www.cnblogs.com/baota/p/6738562.html
Copyright © 2011-2022 走看看