call()
call函数可以调用函数。
function test() {
console.log('测试');
}
test.call(); //test()
call也可以改变this函数指向
const obj = {
msg: '测试'
}
function test() {
console.log(this);
}
test.call(obj);
改变this指向时也可以传参
const obj = {
msg: '测试'
}
function test(x,y) {
console.log(x+y);
}
test.call(obj,1,2); //3
apply()
apply()方法调用一个函数,也可以改变this指向
fun.apply(thisArg,[argsArray])
- thisArg : 在fun函数运行时指定的this值
- argsArray :传递的值,必须包含在数组里面
- 返回值就是函数的返回值,因为它就是调用函数
const obj = {
msg: '测试'
}
function test(x,y) {
console.log(x+y);
}
test.apply(obj,[1,2]); //3
可以利用apply借助于数学内置对象求数组最大值
var arr = [1,4,23,13,14];
var max = Math.max.apply(Math,arr);
bind()
bind()方法不会调用函数,当能改变this指向(不想立即使用函数又想改变this指向可以使用)
fun.bind(thisArg,arg1,arg2)
- thisArg :在fun函数运行时指定的this值
- arg1 , arg2 :传递的其他参数
- 返回由指定的this值和初始化参数改造的原函数拷贝(产生新函数)
const obj = {
msg: '测试'
}
function test() {
console.log(this);
}
var fn = test.bind(obj)
fn();