call、apply、bind
2018-04-07 本文已影响0人
半斋
call、apply、bind
相同的地方
- 三者都是用来改变函数体内 this 对象的值
- 第一个参数都是 this 要指向的对象
- 可以接受更多参数(即第二个开始)来对函数传参
不同的地方 - call 与 apply
两者的却别仅在于接受后续参数方式的不同
call第一个参数是this值没有变化,其余参数都是直接传递,也就是全部列举出来
function sum(x,y){
if(x&&y){
return (this.a + this.b + x + y)
} else{
return (this.a + this.b)
}
}
var obj1 = {
a: 1,
b: 2
}
var obj2 = {
c: 3,
d: 4
}
console.log(sum.call(obj1)) // 3
console.log(sum.call(obj1, obj2.c, obj2.d)) // 10
apply的第一个参数为this值,第二个参数可以是 Array 的实例,也可以使 arguments 对象,也就是伪数组
function sum(x,y){
if(x&&y){
return (this.a + this.b + x + y)
} else{
return (this.a + this.b)
}
}
var obj1 = {
a: 1,
b: 2
}
var obj3 = { // 伪数组
0: 3,
1: 4,
length:2
}
console.log(sum.apply(obj1)) // 3
console.log(sum.apply(obj1, obj3)) // 10
console.log(sum.apply(obj1, [3,4])) // 10 传入数组
// 传入 arguments 对象
function sumall(a,b){
this.a = 1
this.b = 2
return sum.apply(this, arguments)
}
console.log(sumall(3,4))
- bind 与前两者不同的返回值
函数.call() 和 函数.apply() 都是对函数的直接调用
而bind不同,它返回指定了this值的函数
它也可以像call那样传参
function sum(x,y){
if(x&&y){
return (this.a + this.b + x + y)
} else{
return (this.a + this.b)
}
}
var obj1 = {
a: 1,
b: 2
}
var obj2 = {
c: 3,
d: 4
}
var sum2 = sum.bind(obj1)
console.log(sum2()) // 3
console.log(sum2(obj2.c, obj2.d)) // 10