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);
原文地址:https://www.cnblogs.com/zimengxiyu/p/10715961.html