zoukankan      html  css  js  c++  java
  • 《ES6基础教程》之 Call 方法和 Apply 方法

     1     <script type="text/javascript">
     2         // Call方法:
     3         // 语法:call(thisObj[,arg1,arg2,...,argN])
     4         // 定义:调用对象的一个方法,用另一个对象替换当前对象
     5 
     6         // Apply方法:
     7         // 语法:apply([thisObj,argArray])
     8         // 定义:应用某一个对象的一个方法,用另一个对象替换当前对象
     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),结果是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来使用。结果为alert("Cat");
    34         //c,可以实现继承。
    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对象就能直接调用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就实现多继承了。
    63 
    64         call和apply的区别在于call的第二个参数可以是任意类型,而apply的第二个参数必须是数组或者arguments
    65     </script>
  • 相关阅读:
    程序打包
    MFC AfxMessageBox默认标题修改
    Json
    agsXMPP
    xmpp
    afxcomctl32.h与afxcomctl32.inl报错
    jQuery使用
    EChart使用
    C++ tinyXML使用
    electron之Windows下使用 html js css 开发桌面应用程序
  • 原文地址:https://www.cnblogs.com/lvyongbo/p/4701493.html
Copyright © 2011-2022 走看看