zoukankan      html  css  js  c++  java
  • javascript bind函数

    bind函数,顾名思义,用于为调用函数绑定一个作用域,因为this很容易跟丢它原来所在的作用域,直接指向顶层的window对象。具体结论可参见我另一篇博文《javascript的动态this与动态绑定》。本文专注设计一个无侵入的绑定函数。

    window.name = "the window object"
    
    function scopeTest() {
      return this.name
    }
    
    // calling the function in global scope:
    scopeTest()
    // -> "the window object"
    
    var foo = {
      name: "the foo object!",
      otherScopeTest: function() { return this.name }
    }
    
    foo.otherScopeTest()
    // -> "the foo object!"
    

    基于不扩展原生对象的原则,弄了这个bind函数(dom为作用域),用法与Prototype框架的bind差不多。

       dom.bind = function(fn,context){
        //第二个参数如果你喜欢的话,也可以改为thisObject,scope,
        //总之,是一个新的作用域对象
        if (arguments.length < 2 && context===undefined) return fn;
        var method = fn,
        slice = Array.prototype.slice,
        args = slice.call(arguments, 2) ;
        return function(){//这里传入原fn的参数
          var array = slice.call(arguments, 0);
          method.apply(context,args.concat(array))
        }
    

    用法:第一个参数为需要绑定作用域的函数,第二个为window或各种对象,其他参数随意。

    另一个例子:

  • 相关阅读:
    博客CSS样式 二
    产品经理
    HttpClient调用doGet、doPost、JSON传参及获得返回值
    Maven无法下载com.oracle:ojdbc.jar解决方法
    EasyExcel导入导出
    centos7 安装supervisor教程以及常见问题
    Django与Celery的安装使用
    亚马逊广告api v2版php扩展库
    Mac VMware Fusion CentOS7 安装、配置静态IP文档
    常见Web安全问题攻防解析
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/1639541.html
Copyright © 2011-2022 走看看