ref: http://www.cnblogs.com/fighting_cp/archive/2010/09/20/1831844.html
1、call(), apply()都属于Function.prototype的一个方法,它是JavaScript引擎内在实现的,因为属于Function.prototype,所以每个Function对象实例,也就是每个方法都有call, apply属性,即每个函数都包含两个非继承而来的方法:apply()和call(),并且作用一样。
2、区别参数不一样如:foo.call(this, arg1,arg2,arg3) == foo.apply(this, arguments)==this.foo(arg1, arg2, arg3)
用例1:
var name = 'window name';
test1(); // 弹出 window name 此时test1中的this 为 window对象
function test1(){
alert(this.name);
}
var obj = {
name:'obj name'
}
test1.call(obj);//弹出 obj name test中的this为obj ,参数默认为空
//test1.apply(obj) 和call是一样的结果
alert(JSON.stringify(obj));//可以看到obj中并没有test1函数
call 和 apply 的神奇之处 可以无中生有 让obj调用test1函数,但并不拥有该函数
用例2:
<span style="white-space:pre"> </span>function Animal(name){
this.name = name;
this.showName = function(){
alert(this.name);
}
};
function Cat(name){
Animal.call(this,name);
}
//Cat.prototype = new Animal();
function Dog(name){
Animal.call(this,name);
}
//Dog.prototype = new Animal(); // 可以理解为Dog继承Animal
var cat = new Cat("Black Cat");
var dog = new Dog(["Black Dog"]);
cat.showName(); //Black Cat
dog.showName(); //Blcak Dog
alert(cat instanceof Animal); //false
alert(dog instanceof Animal); //false 如果放开上面两行被注释掉的代码 则结果为 true
使用Javascript中构造函数让 cat 、 dog在构造时直接调用animal的构造函数 。