call()与apply()区别

一、方法的定义 
call方法: 
语法:call(thisObj,Object)
定义:调用一个对象的一个方法,以另一个对象替换当前对象。
说明:
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。 

apply方法: 
语法:apply(thisObj,[argArray])
定义:应用某一对象的一个方法,用另一个对象替换当前对象。 
说明: 
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。 
如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。


 

代码示例:

 1 function Animal(name) {
 2     this.name = name;
 3     this.showName = function() {
 4         console.log(this.name);
 5     };
 6 }
 7 
 8 function Cat(name) {
 9     Animal.call(this, name);
10 }
11 Cat.prototype = new Animal();
12 
13 function Dog(name) {
14     Animal.apply(this, name);
15 }
16 Dog.prototype = new Animal();
17 
18 var cat = new Cat("Black Cat"); //call必须是object
19 
20 var dog = new Dog(["Black Dog"]); //apply必须是array
21 
22 cat.showName();
23 dog.showName();
24 
25 console.log(cat instanceof Animal);
26 console.log(dog instanceof Animal);

 


 

模拟call, apply的this替换

 1 function Animal(name) {
 2     this.name = name;
 3     this.showName = function() {
 4         alert(this.name);
 5     };
 6 };
 7 
 8 function Cat(name) {
 9     this.superClass = Animal;
10     this.superClass(name);
11     delete superClass;
12 }
13 
14 var cat = new Cat("Black Cat");
15 
16 cat.showName();

 

 

posted @ 2013-03-05 14:56  小猩猩君  阅读(39659)  评论(0编辑  收藏  举报