十、call 对比 apply 对比 bind
-
共同:功能一致
-
可改变(函数体内的)this指向
-
语法:函数.call()、函数.apply()、函数.bind()
-
-
区别:
-
执行时机:
-
call、apply:立即执行
-
bind:延迟执行,返回函数
-
-
参数:
-
call、bind:普通传参(可有多个参数)
-
apply:数组传参
-
-
var str = 'string'
var obj = {str: 'obj.string'}
function fn(name, age){
this.name = name
this.age = age
console.log(this, this.str)
}
fn() // this = window, this.str = string
fn.call(obj,'call',55) // 立即执行 + 参数
fn.apply(obj,['apply',11]) // 立即执行 + 数组形式的参数
fn.bind(obj,'bind',88) // 不会立即执行,返回的是函数 + 参数
fn.bind(obj,'bind',88)() // 该bind会立即执行,执行的是返回函数
使用场景
-
apply使用情况:当需要数组传参时
var arr = [1,2,4,5,3,65] console.log(Math.max(arr)) //NaN console.log(Math.max.apply(null,arr)) //apply才能接受数组
-
call使用情况:可正常传参,并需要正常执行的情况
-
bind使用情况:当需要函数赋值时
var btn = document.getElementById('btn') var h1 = document.getElementById('h11') // 下面使用bind不需要执行bind返回的函数:DOM点击事件需要的就是函数 btn.onclick = function(){ console.log(this) //无bind情况this = button元素 }.bind(h1) // 将this指向从button元素改为h1元素