zoukankan      html  css  js  c++  java
  • apply,call,bind函数作用与用法

    作用 可以把方法借给其它对象使用,并且改变this的指向

    a.apply(b,[3,2]);//this指向由a变为b, a的方法借给b使用

    实例:

    function add(a,b){
                    console.log(this)
                  return a+b;  
                }
                function sub(a,b){
                  return a-b;  
                }
                //console.log(add(3,2));//指向window
                //console.log(add.apply(sub,[3,2]));//指向sub
                console.log(sub(3,2));//还是原来的方法  想用add方法可以使用用apply,call,bind函数来实现

    使用apply,call,bind可以任意改变函数或方法的执行上下文,即使它没有被绑定到一个实例的原型上。
    function Thing() {
    }
    Thing.prototype.foo = "bar";
    
    
    function logFoo(aStr) {
        console.log(aStr, this.foo);
    }
    
    
    var thing = new Thing();
    logFoo.bind(thing)("using bind"); //logs "using bind bar"
    logFoo.apply(thing, ["using apply"]); //logs "using apply bar"
    logFoo.call(thing, "using call"); //logs "using call bar"
    logFoo("using nothing"); //logs "using nothing undefined"
    

    使用场景:操作arguments

     函数的参数列表arguments是一个类数组对象,虽然它也有“下标”,但它并非真正的数组,所以也不能像数组一样,进行排序操作或者往集合里添加一个新的元素。这种情况下,我们常常会借用Array.prototype对象上的方法。比如想往arguments中添加一个新的元素,通常会借用Array.prototype.push

    (fu在操作arguments的时候,我们经常非常频繁地找Array.prototype对象借用方法。

     (function () {
                Array.prototype.push.call(arguments, 3);
                console.log(arguments);
                // 输出[1,2,3] 
     
    })(1, 2);
  • 相关阅读:
    sublime text3快捷键
    SublimeText3追踪函数工具CTags设置及使用
    mysql的表锁
    ESXI vSphere如何设置虚拟机开机自启动
    gitee支持的开源许可证
    keepalive安装部署踩坑参考
    《牧神记》中诗词大全,有的可能是作者瞎编的
    定位Linux服务器SSH敲命令响应慢的问题
    Crypto-JS——Uncaught Error: Malformed UTF-8 data
    VUE——vue中组件之间的通信方式有哪些
  • 原文地址:https://www.cnblogs.com/zimengxiyu/p/10715961.html
Copyright © 2011-2022 走看看