javaScript的難度開頭---使用call方法和apply方法

來源:互聯網
上載者:User

標籤:highlight   列表   繼承   建構函式   function   測試結果   person   ref   oct   

javaScript  的組合繼承

1,使用  call  方法

      定義:調用一個對象的一個方法,以另一個對象替換當前對象。

<!DOCTYPE html><html>  <head>    <title>借用建構函式</title>    <meta name="keywords" content="keyword1,keyword2,keyword3">    <meta name="description" content="this is my page">    <meta name="content-type" content="text/html; charset=gbk">        <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->  </head>    <body>    <script type="text/javascript">    function Humans(name){    this.name=name;    this.clothing=["夾克","尼龍外套","運動襪套"];    }    function Man(nama,age){    Humans.call(this,name);//借用建構函式的屬性    this.age=age;    }    Man.prototype=new Humans();//繼承Humans函數        var man1=new Man("那盤",23);    man1.clothing.push("皮袍");    alert(man1.clothing);     //輸出:"夾克","尼龍外套","運動襪套","皮袍"        var man2=new Man("馬呐喊",34);    alert(man2.clothing);     //輸出:"夾克","尼龍外套","運動襪套"            </script>  </body></html>

2,apply   方法

     定義:應用某一對象的一個方法,用另一個對象替換當前對象。

<script type="text/javascript">      /*定義一個人類*/      function Person(name,age)      {          this.name=name;          this.age=age;      }     /*定義一個學生類*/     functionStudent(name,age,grade)     {       Person.apply(this,arguments);         this.grade=grade;    }    //建立一個學生類        var student=new Student("qian",21,"一年級");     //測試     alert("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);     //大家可以看到測試結果name:qian  age:21  grade:一年級     //學生類裡面我沒有給name和age屬性賦值啊,為什麼又存在這兩個屬性的值呢,     //這個就是apply的神奇   之處.</script>

  

     分析: Person.apply(this,arguments);

               this:在建立對象在這個時候代表的是student

                     arguments:是一個數組,也就是[“qian”,”21”,”一年級”];

                   也就是通俗一點講就是:用student去執行Person這個類裡面的內容,在Person這個類裡面存在this.name等之類的語句,這樣就將屬性建立到了student對象裡面

3,

    什麼情況下用apply,什麼情況下用call

   在給對象參數的情況下,如果參數的形式是數組的時候,比如apply樣本裡面傳遞了參數arguments,這個參數是數群組類型,並且在調用Person的時候參數的列表是對應一致的(也就是       Person和Student的參數列表前兩位是一致的) 就可以採用 apply , 如果我的Person的參數列表是這樣的(age,name),而Student的參數列表是(name,age,grade),這樣就可以用call來實現了,也就是直接指定參數列表對應值的位置(Person.call(this,age,name,grade));

javaScript的難度開頭---使用call方法和apply方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.