call()
调用一个对象的方法,用另一个对象替换当前对象,可以继承另外一个对象的属性,它的语法是:
function.call(thisArg, arg1, arg2, ...)
- thisArg:在people函数运行时指定this的值
- arg1, arg2:传递的其他参数
- 返回值就是函数的返回值,因为他是调用函数
call可以调用函数如图一所示,改变this指向(图二)
<script>
function people(age,sex) {
console.log(this);
console.log(this.name +` ${sex}今年${age}`);
}
const worker = {
name:'ks',
}
people.call(worker,55,'男')
//可以调用函数也可以改变this指向,简单来说call里面第一个参数是指定this,其余是实参,传递的参数。
</script>
apply()
apply和call()方法一样,只是参数列表不同,语法:
Function.apply(thisArg, [argsArray])
- thisArg:在people函数运行时指定this的值
- argsArray:传递的值必须包含在数组里
- 返回值就是函数的返回值,因为它是调用函数
argArray:这个是数组,它将作为参数传给Function- apply主要和数组有关系,比如使用Math.max()求数组最大值。
说明:如果argArray不是一个有效数组或不是arguments对象,那么将导致一个TypeError,如果没有提供argArray和thisArg任何一个参数,那么Global对象将用作thisArg。
function people(sex,age) {
console.log(this);
console.log(this.name +` ${sex}今年${age}`);
}
const worker = {
name:'ks',
}
people.apply(worker,['男',78])
可以调用函数也可以改变this指向,
const arr = [ 55, 77, 99, 15,]
const max = Math.max.apply(Math,arr)
const min = Math.min.apply(Math,arr)
console.log(`最大值是${max},最小值是${min}`);
bind
function.bind(thisArg, arg1, arg2, ...)
- thisArg:在people函数运行时指定this的值
- arg1, arg2:传递的其他参数
- 返回有指定的this值和初始化参数改造的原函数拷贝(新函数)
- 当只是想改变this指向,并且不想调用这个函数的时候可以使用bind,比如改变定时器内部this的指向.
function people(sex,age) {
console.log(this);
console.log(this.name +` ${sex}今年${age}`);
}
const worker = {
name:'ks',
}
const fn = people.bind(worker,'男',78)
fn()
bind应用举例。
<body>
<button>同意</button>
<script>
const btn = document.querySelector('button')
btn.addEventListener('click',function(){
console.log(this);
this.disabled = true
window.setTimeout(function () {
this.disabled = false
}.bind(this) ,2000)
})
</script>
call、apply、bind总结
相同点:
- 都是改this指向
区别:
- call、apply会立即执行,并且改变函数内部this指向。
- call和appley传递的参数不同,call传递参数arg1, arg2...形式,apply必须是数组形式[argsArray]
- bind不会调用函数,可以改变函数内部this指向
- call可以继承
- bind改变setTimeout的执行,点击事件里面包含setTimeout,setTimeout默认指向windwos,可以通过bind指向点击对象
应用场景
- call调用函数并且可以传递参数
- apply和数组有关系,可以利用apply求最大值最小值
- bind 不会调用函数,但是还想改变this指向,例如定时器内的this指向。
认知有限,欢迎指正 谢谢