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