定义
ECMAScript规范给所有函数都定义了call 与 apply 两个方法,call与apply的第一个参数都是需要调用的函数对象,在函数体内这个参数就是this的值,剩余的参数是需要传递给函数的值,具体如下:
call方法:
语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定义:以传入对象作为当前对象去调用其他对象的方法。
注:如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。
apply方法:
语法:apply([thisObj[,argArray]])
定义:以传入对象作为当前对象去调用其他对象的方法。
注:
1. 如果 argArray 不是一个有效的数组或者不是arguments 对象,那么将导致一个 TypeError;
2. 如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。
区别
从上文中可看出两个方法基本上是一个意思,区别在于 call 的第二个参数可以是任意类型,而apply的第二个参数必须是数组,也可以是arguments。
用途
函数替换
function add(a,b) { alert(a+b); } function sub(a,b) { alert(a-b); } add.call(sub,3,1); // => add(3, 1) => alert(4) add.apply(sub, [3,1]) // => add(3,1) => alert(4)
这个例子中就是用 add 来替换 sub
方法借用
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,","); animal.showName.apply(cat, []); // => alert(“cat”)
原来cat是没有showName() 方法,现在通过call或apply把animal 的showName()方法借到 cat上来执行,同时也将showName方法的上下文从animal改为cat,故showName中的this指向cat,所以this.name 应该是 Cat
实现继承
function Animal(name){ this.name = name; this.showName = function(){ alert(this.name); } } function Cat(name){ Animal.call(this, name); // Animal.apply(this,[name]); } var cat = new Cat("Black Cat"); cat.showName(); // => alert(“Black Cat”)
Animal.call(this) 的意思就是使用 this对象代替Animal对象,那么 Cat中自然就有Animal的所有属性和方法。
多重继承
function Father() { this.showSub = unction(a,b){ alert(a-b); } } function Mother(){ this.showAdd = function(a,b){ alert(a+b); } } function Child(){ Father.call(this); Mother.call(this); }