javascript面向对象中继承实现的几种方式


1.原型链继承:

    function teacher(name){  
        this.name = name;  
    }  
    teacher.prototype.sayName = function(){  
        alert(this.name);
    }   
      
    function student(name){  
        this.name = name;  
    }  
student.prototype = new teacher() var student1 = new student("xiaolan"); student1.sayName(); // name is xiaolan

 2.组合式继承:是开发中最长用的

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

         Person.prototype.getName = function () {
             return this.name;
         };

        function Parent (age) {
            Person.call(this,'老明');  //这一步很关键
            this.age = age;
        };

        Parent.prototype = new Person('老明');  //这一步也很关键
        var result = new Parent(24);
        console.log(result.name);    //老明
        console.log(result.getName());  //老明
        console.log(result.age);    //24

        var result1 = new Parent(25);   //通过借用构造函数都有自己的属性,通过原型享用公共的方法
        console.log(result1.name);  //老明
 

 3.call和applay继承:

 

function teacher(name){
    this.name=name;
    this.sayName=function(){
        alert(this.name);
    }
}

function student(age){
        teacher.call(this,"小明");
        this.age=age;
}
    var ss=new student("30");
    ss.sayName();//小明
    alert(ss.age);//30

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM