apply call bind方法的区别和含义

用法示例与解析:

apply

function applyTest(a,b){
    console.log(this.pro, a,b)
};
applyTest.apply({pro: 'apply'}, [1, 2]);  //apply 1 2

call

function callTest(a, b){
    console.log(this.pro, a, b)  
};
callTest.call({pro: 'call'}, 1, 2); //call 1 2

bind

function bindTest(a, b){
    console.log(this.pro, a, b)  
};
var mid = bindTest.bind({pro: 'bind'}, 1);
mid(2); //bind 1 2

apply和call以及bind都是Function.prototype的方法函数,每个继承自Function的函数都有这三个方法。

相同点:

  都可以改变函数内部的this指向

  所传入的第一个参数都是this所要指向的那个对象

不同点:

  apply和call只要调用就会立即执行函数得到结果,而bind只是会返回一个函数,需要再次执行这个函数才会运行函数。

  apply传入的第二个参数是可选的,但是只能是数组形式或者是arguments;

  call的第二个以及之后的参数是以单个参数形式传入的,与原函数的参数一一对应;

  bind的参数可以在不同阶段加入,但与原函数的参数也是一一对应的。

用途:

  在多个对象要执行同一个方法的时候可以不给每个对象都填加此方法,灵活度高

  apply可以实现的操作:

数组的降纬
var
sou=[[1,2],[3,4],[5,6]]; var res=Array.prototype.concat.apply(res, sou) console.log(res); //[1,2,3,4,5,6]

比较两个数组中元素的大小
var sou=[5,9,4,3.2,5];
var res = Math.max.apply(null, sou);
console.log(res) //9

实现bind函数
Function.prototype.bind
||
Function.prototype.bind=function(tar){
  var fn=this
  return(
    function(){
      fn.apply(tar, arguments)
    }
  )
}

  

原文地址:https://www.cnblogs.com/zhaozhipeng/p/8066541.html