js 中繼承的幾種方式


繼承的方式一共有三種:

 一、原型繼承

      通過prototype   來實現繼承。

    

   function Person(name,age) {
         this.name=name;
         this.age=age;
    }

   Person.prototype.sayHello=function(){
         alert (''使用原型得到Name:'' + this.name);

    }

    var per = new Person("馬小倩",21);
          per.sayHello();//輸出:使用原型得到Name:馬小倩 


    function Student(){}

       Student.prototype=new Person("洪如彤",21);  //實現原型繼承
        
       var  stu = new Student();

           Student.prototype.grade=5;  

        Student.prototype.intr=function(){  
        alert(this.grade);  
    }  


      stu.sayHello();//輸出:使用原型得到Name:洪如彤  
    stu.intr();//輸出:5  

     

 

二、構造函數實現繼承

   

 function Person(name,age) {
         this.name=name;
         this.age=age;
    }

   Person.prototype.sayHello=function(){
         alert (''使用原型得到Name:'' + this.name);

    }

    var per = new Person("馬小倩",21);
          per.sayHello();//輸出:使用原型得到Name:馬小倩

 

    三、  通過call、apply  實現繼承

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM