1、语法格式
call方法
语法:call(thisObj,arg1,arg2,arg3,...) 第一个参数为对象,后面紧跟着需要传入的参数
定义:调用一个对象的方法,以另一个对象替换当前对象
说明:如果没有提供 thisObj 参数,那么Global对象被用作 thisObj,同时args可以省略,即call(thisObj)
apply方法
语法:apply(thisObj,[arg1,arg2,arg3,...]) 第一个参数为对象,第二个参数为数组集合,包含所有需要传入的参数
定义:调用一个对象的方法,以另一个对象替换当前对象
说明:如果 [arg1,arg2,arg3,...]不是一个有效的数组或者不是 arguments 对象,那么将导致一个TypeError
如果没有提供 thisObj 参数,那么 Global对象被用作 thisObj,同时[arg1,arg2,arg3,...]可以省略,即apply(thisObj)
2、简单示例
var x = 10;
function A() {
return this.x;
}
A();//此时的this指向Global对象
var thisObj = {
x: 20
}
A.call(thisObj);
A.apply(thisObj);
//输出结果:
10
20
20
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
add(20, 10)
subtract(20, 10)
add.apply(subtract, [20, 10]) //subtract调用add方法
subtract.apply(add, [20, 10])
add.call(subtract, 20, 10)
subtract.call(add, 20, 10)
输出结果:
30
10
30
10
30
10
3、高级实例
function Animal() {
this.name = "Animal";
this.showName = function() {
alert(this.name);
}
}
function Cat() {
this.name = "Cat";
}
var animal = new Animal();
var cat = new Cat();
//输入结果为"Cat",将原本属于Animal对象的showName()方法交给对象cat来使用了
animal.showName.call(cat, ",");
animal.showName.apply(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();
//输出:Black Cat
//多次继承
function subtract() {
this.showSub = function(a, b) {
alert(a - b);
}
}
function add() {
this.showAdd = function(a, b) {
alert(a + b);
}
}
function union() {
subtract.apply(this);
add.apply(this);
// subtract.call(this);
//add.call(this);
}
var c2 = new union();
c2.showSub(3, 1); //2
c2.showAdd(3, 1); //4