call()、apply()、bind()

89 阅读1分钟

1.call()、apply()、bind() 都是用来重定向 this

let obj={
	name:'刘枫',
	age:'25',
	_fun:function(){
		console.log(this.name+'年龄'+this.age);
		}
	}
let objx={
	name:'李杰',
	age:24
}

obj._fun.call(objx); //李杰年龄24
obj._fun.apply(objx); //李杰年龄24
obj._fun.bind(objx)(); //李杰年龄24
总结 : bind方法返回一个新函数必须执行它 ();

2.call 、bind 、 apply 传参比较

let obj={
	name:'刘枫',
	age:'25',
	_fun:function(likes,noLike){
		console.log(this.name+'年龄'+this.age+'喜欢'+likes+'不喜欢'+noLike);
		}
	}
let objx={
	name:'李杰',
	age:24
}

obj._fun.call(objx,'放屁','干活'); //李杰年龄24喜欢放屁不喜欢干活
obj._fun.apply(objx,['放屁','干活']); //李杰年龄24喜欢放屁不喜欢干活
obj._fun.bind(objx,'放屁','干活')(); //李杰年龄24喜欢放屁不喜欢干活
总结:
call 和 bind 的传参方法一样
apply 的参数必须要放到数组里面穿过去

找出数组最小值的下标

let arr = [151, 511, 220, 515, 52]
console.log(arr)
function getMinidx(arr) {
    let index = [].indexOf.call(arr, Math.min.apply(null, arr));
    console.log(index);//4
}
window.onload = function () {
    getMinidx(arr)
}