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

 

posted @ 2018-05-10 19:05  梅梅姐  阅读(2034)  评论(0编辑  收藏  举报