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!  
  • 相关阅读:
    [tensorflow] tf.gather使用方法
    Tensorflow Dataset.from_generator使用示例
    np.random.rand()函数
    python类
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
    KNN算法
    Qt编写数据可视化大屏界面电子看板11-自定义控件
    Qt编写数据可视化大屏界面电子看板10-改造QCustomPlot
    Qt编写数据可视化大屏界面电子看板9-曲线效果
    闲谈Monaco Editor-基本使用
  • 原文地址:https://www.cnblogs.com/jiangxiaobo/p/6413618.html
Copyright © 2011-2022 走看看