這篇文章主要介紹了JavaScript中函數(shù)(Function)的apply與call理解,本文講解了JavaScript函數(shù)調(diào)用分為4中模式以及通過apply和call實(shí)現(xiàn)擴(kuò)展和繼承兩方面,需要的朋友可以參考下
JavaScript函數(shù)調(diào)用分為4中模式:
1. 方法調(diào)用模式:即對(duì)象包含方法屬性,Obj.methodName()或者Obj[methodName]()。
2. 函數(shù)調(diào)用模式:即methodName()。
3. 構(gòu)造器調(diào)用模式:即new MethodName()。
4. apply和call調(diào)用模式:即ObjA.apply(ObjB,args[])或者ObjA.call(ObjB,arg1,arg2...)。
函數(shù)調(diào)用時(shí),除了接收形式參數(shù)外,還會(huì)接收this和arguments。其中this為函數(shù)對(duì)象上下文,arguments為實(shí)際參數(shù)。
apply和call實(shí)現(xiàn)同樣的功能,即切換函數(shù)對(duì)象的上下文(this指向的引用),區(qū)別在于形式參數(shù)不一樣。apply為arguments或者數(shù)組,call為以逗號(hào)隔開多個(gè)單獨(dú)形式參數(shù)。
- function add(c)
- {
- alert(this.a+this.b+c);
- }
- var test={a:1,b:2}
- add.call(test,3);
在執(zhí)行add.call(test,3); 之前add和test都屬于window下,此時(shí)this指向window。add.call(test,3); 執(zhí)行時(shí),進(jìn)入add方法體,此時(shí)this由window切換為test,此時(shí)this.a=test.a,this.b=test.b,c為形式參數(shù)傳入的值,即alert()的結(jié)果為1+2+3=6。apply也是一樣的功能。
通過apply和call實(shí)現(xiàn)擴(kuò)展和繼承:
- 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");//執(zhí)行時(shí),Cat函數(shù)體的this由window切換為Cat{},
- // Animal函數(shù)體的this.name通過形式參數(shù)傳入即為Black Cat,最終cat
- //得到的結(jié)果為cat=Cat{name:"Black Cat",showName: function(){ alert(this.name);},
- cat.showName();//執(zhí)行時(shí)this由window切換為
- //Cat{name:"Black Cat",showName: function(){ alert(this.name);} 此時(shí)this.name
- //為this.name=Cat.name,因此為Black Cat。
新聞熱點(diǎn)
疑難解答
圖片精選