zoukankan      html  css  js  c++  java
  • js原生函数bind

    /*在javascript中,函数总是在一个特殊的上下文执行(称为执行上下文),如果你将一个对象的函数赋值给另外一个变量的话,这个函数的执行上下文就变为这个变量的上下文了。下面的一个例子能很好的说明这个问题  
    代码如下:*/  
      
    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!"   
    var foo_otherScopeTest = foo.otherScopeTest;   
    foo_otherScopeTest();   
    // –> "the window object"   
      
    /*如果你希望将一个对象的函数赋值给另外一个变量后,这个函数的执行上下文仍然为这个对象,那么就需要用到bind方法。   
    bind的实现如下:   
    复制代码 代码如下:*/  
      
    // The .bind method from Prototype.js   
    Function.prototype.bind = function(){   
    var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();   
    return function(){   
    return fn.apply(object,   
    args.concat(Array.prototype.slice.call(arguments)));   
    };   
    };   
      
    /*使用示例:   
    复制代码 代码如下:  */
        
      var obj = {   
        name: 'A nice demo',   
        fx: function() {   
            alert(this.name);   
        }   
      };   
      
      window.name = 'I am such a beautiful window!';   
      
      function runFx(f) {   
        f();   
      }   
      function fx(){  
        alert(this.name);    
      }  
      var fx2 = obj.fx.bind(obj);   
      runFx(obj.fx); // I am such a beautiful window!  
      runFx(fx2); // A nice demo  
      runFx(fx);// I am such a beautiful window!  
  • 相关阅读:
    nsis打包
    学习记录:ST表
    学习记录:快速幂
    学习记录:哈夫曼树
    学习记录:二叉树
    学习记录:康托展开 与 逆康托展开
    堆排序简介
    动态规划水题集
    lower_bound( ) 与 upper_bound( )
    琐碎的一点技巧
  • 原文地址:https://www.cnblogs.com/jiangxiaobo/p/6413618.html
Copyright © 2011-2022 走看看