1. 三个都是函数自带的方法,用于改变函数的this指向(即改变函数作用域)。
2. call 与 apply 用法类似, 略有区别
func.apply(thisObj, [arg1,arg2,arg3])
func.call(thisObj, arg1, arg2, arg3)
相同点: 第一个参数都是thisObj, 代表函数func 运行时指定的this
值。
PS thisObj并不一定是该函数执行时真正的this
值,非严格模式下:
1)thisObj不传或者为null 或
undefined
,会自动指向全局对象(window),
2)thisObj 为原始值(数字,字符串,布尔值),
会指向该原始值的自动包装对象。
function a(){
console.log(this); //输出函数a中的this对象
}
function b(){}
var c={name:"call"}; //定义对象c
a.call(); //window
a.call(null); //window
a.call(undefined); //window
a.call(1); //Number
a.call(''); //String
a.call(true); //Boolean
a.call(b); //function b(){}
a.call(c); //Object
不同点:call()
方法接受的是参数列表,apply()
方法接受的是一个参数数组
3. 应用场景
var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]
应用(apply) Math.min/Math.max 内置函数求解最大值,最小值
var max = Math.max.apply(null, numbers); /* 基本等同于 Math.max(numbers[0], ...) 或 Math.max(5, 6, ..) */
var min = Math.min.apply(null, numbers);
4. bind()
方法创建一个新的函数,在调用时设置this
关键字为提供的值。并在调用新函数时,将给定参数列表作为原函数的参数序列的前若干项。
function.bind(thisObj, arg1, arg2, arg3)
PS 1) 与call apply 不同 , bind 返回值时一个函数,apply 与 call 是将原来的函数在新作用域下调用一次。
2) 与call apply 不同, bind 返回的新函数, 并且新函数的作用域保存不变(被绑定了)
var a =1;
var b=2;
function f() {console.log(this.a,this.b)};
var c = {a:3,b:4};
var d = f.bind(c)
d() // 3 4
f() // 1 2
function f(x,y) {console.log(this.a,this.b,x,y)};
var d = f.bind(c)
d() // 3 4 undefined undefined
var d = f.bind(c,5,6)
d() // 1 3 4 5 6
d(7,8) // 3 4 5 6