通过实例理解javascript 的call()与apply()

美好的文章不记录确实是个遗憾,尤其是优美的,看的懂了解 却灵活运用的人不多,哎!

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

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

<html>
<head>
<script language="javascript">
/**定义一个animal类*/
function Animal(){
    this.name = "Animal";
    this.showName = function(){
        alert(this.name);
    }
}
/**定义一个Cat类*/
function Cat(){
    this.name = "Cat";
}

/**创建两个类对象*/
var animal = new Animal();
var cat = new Cat();

//通过call或apply方法,将原本属于Animal对象的showName()方法交给当前对象cat来使用了。
//输入结果为"Cat"
animal.showName.call(cat,",");
//animal.showName.apply(cat,[]);
 

</script>
</head>
<body></body>
</html>

以上代码无论是采用animal.showName.call或是animal.showName.apply方法,运行的结果都是输出一个"Cat"的字符串。说明showName方法的调用者被换成了cat对象,而不是最初定义它的animal了。这就是call和apply方法的妙用! 

三、小结: 
call和apply方法通常被用来实现类似继承一样的功能,以达到代码复用的功效。它们的区别主要体现在参数上。

附加代码:

<html>  
<head>  
<script language="javascript">  

function Animal(name){  
    this.name = name;  
    this.showName = function(){  
        alert(this.name);  
    }  
}  

function Cat(name){
    Animal.call(this, name);
}  

Cat.prototype = new Animal();

var cat = new Cat("Black Cat");  

cat.showName();

alert(cat instanceof Animal);

  
</script>  
</head>  
<body></body>  
</html>  

群里请教记录

如,arguements,和array的slice 

arguments是没有slice的,但有length属性。
 
arguements这个是获取函数的参数 

就可以用array的slice对arguments进行操作。 

Array.prototype.slice.call(arguments) 

Array.prototype.slice.call(arguments,0) 

我觉得这个好理解一点 你可以说apply是一个复制的方法 

Array.prototype.slice.call(arguments) 这句相当于arguments有个slice的方法 

我是说“类似”继承 

apply,call,转换后就是类似o.xxx这种的。 

继承是父子间的。 这个,可以任何关系间的 

就接用别人函数,参数用你的 

 转自iteye http://ll-feng.iteye.com/blog/599108

附加js继承:

function baseClass(a,b){
this.a=a;
this.b=b;
this.init=function(name){
 return name;
 }
}


function exClass(x,y){
this.a=baseClass;
this.a(x,y);
}

var sp=new exClass(1,2);
alert(sp.init("sp")+"--"+sp.a);


function baseClass1(a,b)
{
this.a=a;
this.b=b;
}
baseClass1.prototype={
init:function(name){
return name;
}
}

function exClass1(x,y){
baseClass1.call(this, x,y);
}

exClass1.prototype = new baseClass1();

var sp= new exClass1(3,6);  
原文地址:https://www.cnblogs.com/y112102/p/2988551.html