Home  >  Article  >  Web Front-end  >  JavaScript中函数(Function)的apply与call理解_javascript技巧

JavaScript中函数(Function)的apply与call理解_javascript技巧

WBOY
WBOYOriginal
2016-05-16 15:50:521298browse

JavaScript函数调用分为4中模式:

1. 方法调用模式:即对象包含方法属性,Obj.methodName()或者Obj[methodName]()。
2. 函数调用模式:即methodName()。
3. 构造器调用模式:即new MethodName()。
4. apply和call调用模式:即ObjA.apply(ObjB,args[])或者ObjA.call(ObjB,arg1,arg2...)。

函数调用时,除了接收形式参数外,还会接收this和arguments。其中this为函数对象上下文,arguments为实际参数。
apply和call实现同样的功能,即切换函数对象的上下文(this指向的引用),区别在于形式参数不一样。apply为arguments或者数组,call为以逗号隔开多个单独形式参数。

function add(c) 
{ 
  alert(this.a+this.b+c); 
} 
var test={a:1,b:2} 
add.call(test,3);


在执行add.call(test,3); 之前add和test都属于window下,此时this指向window。add.call(test,3); 执行时,进入add方法体,此时this由window切换为test,此时this.a=test.a,this.b=test.b,c为形式参数传入的值,即alert()的结果为1+2+3=6。apply也是一样的功能。
 
通过apply和call实现扩展和继承:

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函数体的this由window切换为Cat{}, 
// Animal函数体的this.name通过形式参数传入即为Black Cat,最终cat 
 //得到的结果为cat=Cat{name:"Black Cat",showName: function(){ alert(this.name);}, 
 cat.showName();//执行时this由window切换为 
 //Cat{name:"Black Cat",showName: function(){ alert(this.name);} 此时this.name 
 //为this.name=Cat.name,因此为Black Cat。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn