《ES6基础教程》之 Call 方法和 Apply 方法
生活随笔
收集整理的這篇文章主要介紹了
《ES6基础教程》之 Call 方法和 Apply 方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1 <script type="text/javascript">
2 // Call方法:
3 // 語法:call(thisObj[,arg1,arg2,...,argN])
4 // 定義:調(diào)用對象的一個方法,用另一個對象替換當(dāng)前對象
5
6 // Apply方法:
7 // 語法:apply([thisObj,argArray])
8 // 定義:應(yīng)用某一個對象的一個方法,用另一個對象替換當(dāng)前對象
9
10 //a,
11 function add (a,b) {
12 alert(a+b);
13 }
14 function sub(a,b){
15 alert(a-b);
16 }
17 add.call(sub,3,1);
18 用add來替換sub,add.call(sub,3,1)==add(3,1),結(jié)果是alert(4);
19 //b,
20 function Animal(){
21 this.name="Animal";
22 this.showName=function(){
23 alert(this.name);
24 }
25 }
26 function Cat(){
27 this.name="Cat";
28 }
29 var animal=new Animal();
30 var cat=new Cat();
31
32 animal.showName.call(cat);
33 // 通過call或者apply方法,將原本屬于Animal對象的showName()方法交給對象cat來使用。結(jié)果為alert("Cat");
34 //c,可以實現(xiàn)繼承。
35 function Animal(name){
36 this.name=name;
37 this.showName=function(){
38 alert(this.name);
39 }
40 }
41 function Cat(name){
42 Animal.call(this,name);
43 }
44 var cat=new Cat("Black Cat");
45 cat.showName();
46 //Animal.call(this)的意思是使用Animal對象代替this對象,那么Cat中就有了Animal的所有方法和屬性了,Cat對象就能直接調(diào)用Animal的方法和屬性了。
47 //d,多重繼承
48 function Class10(){
49 this.showSub=function(a,b){
50 alert(a-b);
51 }
52 }
53 function Class11(){
54 this.showAdd=function(a,b){
55 alert(a+b);
56 }
57 }
58 function Class2(){
59 Class10.call(this);
60 Class11.call(this);
61 }
62 //使用兩個call就實現(xiàn)多繼承了。
63
64 call和apply的區(qū)別在于call的第二個參數(shù)可以是任意類型,而apply的第二個參數(shù)必須是數(shù)組或者arguments
65 </script>
?
轉(zhuǎn)載于:https://www.cnblogs.com/lvyongbo/p/4701493.html
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的《ES6基础教程》之 Call 方法和 Apply 方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 操作系统之内存管理:5、虚拟存储技术(请
- 下一篇: 计组之存储系统:2、SRAM(区别、栅极