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