教育行業(yè)A股IPO第一股(股票代碼 003032)

全國咨詢/投訴熱線:400-618-4000

UI培訓(xùn)之JS中的call()和apply()方法

更新時(shí)間:2016年03月10日16時(shí)39分 來源:傳智播客UI培訓(xùn)學(xué)院 瀏覽次數(shù):

1、方法定義
call方法:
語法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定義:調(diào)用一個(gè)對(duì)象的一個(gè)方法,以另一個(gè)對(duì)象替換當(dāng)前對(duì)象。
說明:
call 方法可以用來代替另一個(gè)對(duì)象調(diào)用一個(gè)方法。call 方法可將一個(gè)函數(shù)的對(duì)象上下文從初始的上下文改變?yōu)橛?thisObj 指定的新對(duì)象。
如果沒有提供 thisObj 參數(shù),那么 Global 對(duì)象被用作 thisObj。
apply方法:
語法:apply([thisObj[,argArray]])
定義:應(yīng)用某一對(duì)象的一個(gè)方法,用另一個(gè)對(duì)象替換當(dāng)前對(duì)象。
說明:
如果 argArray 不是一個(gè)有效的數(shù)組或者不是 arguments 對(duì)象,那么將導(dǎo)致一個(gè) TypeError。
如果沒有提供 argArray 和 thisObj 任何一個(gè)參數(shù),那么 Global 對(duì)象將被用作 thisObj, 并且無法被傳遞任何參數(shù)。
2、常用實(shí)例
a、
javascript代碼   
1. function add(a,b) 
2.
3. alert(a+b); 
4.
5. function sub(a,b) 
6.
7. alert(a-b); 
8.
9.
10. add.call(sub,3,1); 
這個(gè)例子中的意思就是用 add 來替換 sub,add.call(sub,3,1) == add(3,1) ,所以運(yùn)行結(jié)果為:alert(4); // 注意:js 中的函數(shù)其實(shí)是對(duì)象,函數(shù)名是對(duì) Function 對(duì)象的引用。
b、
javascript代碼   
1. function Animal(){ 
2. this.name = "Animal"; 
3. this.showName = function(){ 
4. alert(this.name); 
5.
6.
7.
8. function Cat(){ 
9. this.name = "Cat"; 
10.
11.
12. var animal = new Animal(); 
13. var cat = new Cat(); 
14.
15. //通過call或apply方法,將原本屬于Animal對(duì)象的showName()方法交給對(duì)象cat來使用了。 
16. //輸入結(jié)果為"Cat" 
17. animal.showName.call(cat,","); 
18. //animal.showName.apply(cat,[]); 
call 的意思是把 animal 的方法放到cat上執(zhí)行,原來cat是沒有showName() 方法,現(xiàn)在是把a(bǔ)nimal 的showName()方法放到 cat上來執(zhí)行,所以this.name 應(yīng)該是 Cat
c、實(shí)現(xiàn)繼承
javascript代碼   
1. function Animal(name){ 
2. this.name = name; 
3. this.showName = function(){ 
4. alert(this.name); 
5.
6.
7.
8. function Cat(name){ 
9. Animal.call(this, name); 
10.
11.
12. var cat = new Cat("Black Cat"); 
13. cat.showName(); 
Animal.call(this) 的意思就是使用 Animal對(duì)象代替this對(duì)象,那么 Cat中不就有Animal的所有屬性和方法了嗎,Cat對(duì)象就能夠直接調(diào)用Animal的方法以及屬性了.
d、多重繼承
javascript代碼   
1. function Class10() 
2.
3. this.showSub = function(a,b) 
4.
5. alert(a-b); 
6.
7.
8.
9. function Class11() 
10.
11. this.showAdd = function(a,b) 
12.
13. alert(a+b); 
14.
15.
16.
17. function Class2() 
18.
19. Class10.call(this); 
20. Class11.call(this); 
21.
很簡單,使用兩個(gè) call 就實(shí)現(xiàn)多重繼承了
當(dāng)然,js的繼承還有其他方法,例如使用原型鏈,這個(gè)不屬于本文的范疇,只是在此說明call 的用法。說了call ,當(dāng)然還有 apply,這兩個(gè)方法基本上是一個(gè)意思,區(qū)別在于 call 的第二個(gè)參數(shù)可以是任意類型,而apply的第二個(gè)參數(shù)必須是數(shù)組,也可以是arguments
還有 callee,caller..



本文版權(quán)歸傳智播客UI培訓(xùn)學(xué)院所有,歡迎轉(zhuǎn)載,轉(zhuǎn)載請(qǐng)注明作者出處。謝謝!
作者:傳智播客UI培訓(xùn)學(xué)院
首發(fā):http://oisangadgets.com/ui 
0 分享到:
和我們?cè)诰€交談!