apply,call,bind

https://www.cnblogs.com/chenhuichao/p/8493095.html

call、apply和bind是Function对象自带的三个方法,都是为了改变函数体内部 this 的指向。
apply 、 call 、bind 三者第一个参数都是 this 要指向的对象,也就是想指定的上下文;
apply 、 call 、bind 三者都可以利用后续参数传参;
bind 是返回对应 函数,便于稍后调用;apply 、call 则是立即调用 。

1.bind会创建一个 新函数,当调用这个新函数时,新函数会以创建它时传入 bind() 方法的第一个参数 作为 this,传入 bind() 方法的 第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数。

let bar = function(){
    console.log(this.x);
};
let foo = {
    x:3
};
bar(); // undefined
let func = bar.bind(foo); 
func(); // 3

 2.call 传入参数列表,apply 传入数组

let array1 = [12,'foo'];
let array2 = ['Doe',100];

Array.prototype.push.call(array1, 'Doe',100)
Array.prototype.push.apply(array1, array2)

 3.更简单直观的演示

let a = {
  name: 'a'
}
function b() {
  let arr = Array.from(arguments)
  console.log(arr, this.name)
}
let c = b.bind(a)
b.call(a, 1, 2, 3) //  [1, 2, 3] "a"
b.apply(a, [1, 2, 3]) //  [1, 2, 3] "a"
c() // [] 'a'
原文地址:https://www.cnblogs.com/qxp140605/p/11239310.html