1、什么情况下需要使用apply 或者 call?
在一个函数对象中调用另一个函数对象 类似于构造函数的继承
function Animal(){
this.type='动物';
}
function Cat(name,color){
//apply 是将父函数的对象绑定在子对象里面
Animal.apply(this);
this.name=name;
this.color=color;
}
var cat1=new Cat("大明","黄色");
console.log(cat1.type); // 动物
function Animal(){
this.type='动物';
}
function Cat(name,color){
//call 是将父函数的对象绑定在子对象里面
Animal.call(this);
this.name=name;
this.color=color;
}
var cat1=new Cat("小明","红色");
console.log(cat1.type); // 动物
function Person(name, age) {
this.name = name;
this.age = age;
}
function Student(name, age, score) {
//Person(name,score);注意这里不能直接这样调用 这样调用函数的this指向了window 而不是构造函数
Person.call(this, name, score);
this.score = score;
}
var s1=new Student('gw','19','10');
console.dir(s1);
2、使用apply 和 call的区别是什么?
两者区别参数不同 apply 可以传数组 call 一个个传
网友评论