定义:调用一个对象的一个方法,用另一个对象替换当前对象
意义:改变执行上下文(this)
不同点:call可以传入多个参数,从第二参数开始会映射到func的参数上
function test (a,b,c) {}
test.call(obj, 1,2,3)
// function接收到的参数实际上是 1,2,3
test.call(obj, [1,2,3])
// function接收到的参数实际上是 [1,2,3],undefined,undefined
apply方法最多两个参数,第二参数是数组或者类数组
test.apply(obj, [1,2,3])
// function接收到的参数实际上是 1,2,3
test.apply(obj, {
0: 1,
1: 2,
2: 3,
length: 3
})
// function接收到的参数实际上是 1,2,3
对象继承
function parent(){
this.num = 1
this.sun = function(){
console.log(this.num+1)
}
}
function son(){
parent.call(this)//将this指向parent函数,继承parent内的方法和变量
this.sun()
this.p = 5
this.fox = function(){//son自己的方法
console.log(this.p+3)
}
fox()
}
son()//2 8