bind, call, apply 总结
bind介绍
function foo(c, d) {
this.b = 100
console.log(this.a)
console.log(this.b)
console.log(c)
console.log(d)
}
// 我们将foo bind到{a: 1}
var func = foo.bind({ a: 1 }, '1st');
func('2nd'); // 1 100 1st 2nd
// 即使再次call也不能改变this。
func.call({ a: 2 }, '3rd'); // 1 100 1st 3rd
// 当 bind 返回的函数作为构造函数的时候,
// bind 时指定的 this 值会失效,但传入的参数依然生效。
// 所以使用func为构造函数时,this不会指向{a: 1}对象,this.a的值为undefined。如下
// new func('4th'); //undefined 100 1st 4thcall与apply
常见应用场景
合并两个数组
获取数组中的最大值或最小值
类数组对象转数组
Last updated