Call方法:
语法:call(thisObj[,arg1,arg2,...,argN])
定义:调用对象的一个方法,用另一个对象替换当前对象
Apply方法:
语法:apply([thisObj,argArray])
定义:应用某一个对象的一个方法,用另一个对象替换当前对象
call和apply的区别在于call的第二个参数可以是任意类型,而apply的第二个参数必须是数组或者arguments
arguments 是函数中自动创建的一种类数组对象,用来接收函数所传入的参数值。
arguments[i]:获得下标对应的参数值;
arguments.length:获得所传入函数的参数个数;
arguments不是数组类型,不可使用数组API!
用来替换使用
function add (a,b) {
alert(a+b);
}
function sub (a,b) {
alert(a-b);
}
add.call(sub,3,1);
//用add来替换sub,add.call(sub,3,1)==add(3,1),结果是alert(4);
使用其他对象的方法
function Animal(){
this.name="Animal";
this.showName=function(){
alert(this.name);
}
}
function Cat(){
this.name="Cat";
}
var animal=new Animal();
var cat=new Cat();
animal.showName.call(cat);
// 通过call或者apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用。结果为alert("Cat");实现继承
function Animal(name){
this.name=name;
this.showName=function(){
alert(this.name);
}
}
function Cat(name){
Animal.call(this,name);
}
var cat=new Cat("Black Cat");
cat.showName();
//Animal.call(this)的意思是使用Animal对象代替this对象,
//那么Cat中就有了Animal的所有方法和属性了,Cat对象就能直接调用Animal的方法和属性了。多重继承
function Class10(){
this.showSub=function(a,b){
alert(a-b);
}
}
function Class11(){
this.showAdd=function(a,b){
alert(a+b);
}
}
function Class2(){
Class10.call(this);
Class11.call(this);
}
//使用两个call就实现多继承了。
版权声明:本文为qq_42822007原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。