call 和 apply 都是为了改变某个函数运行时的 context 即上下文而存在的,换句话说,就是为了改变函数体内部 this 的指向
两者区别在于接收参数方式不同:
call() 方法分别接受参数。
apply() 方法接受数组形式的参数。
function A(name,age){
this.name = name;
this.age = age;
this.go = function(){
console.log(this==b);//true
console.log(this.name+this.age+'在晨跑中...')//jack21岁在晨跑中...
}
}
function B(name,age){
//A.call(this,name,age)
A.apply(this,arguments);
/*
这里的this对象代替A里实例化出的对象
arguments数组作为参数传递给A
*/
}
var b = new B('jack','21岁');
b.go();