javascript實現繼承的三種方式

1、原型鏈繼承 javascript

 

function Parent(){} 
function Child(){} 
Child.prototype = new Parent(); 

經過對象child的prototype屬性指向父對象parent的實例,使child對象的實例經過原型鏈訪問到父對象構造所定義的屬性、方法等。java

2、使用apply、call方法 數組

js中call和apply均可以實現繼承,惟一的一點參數不一樣,func.call(func1,var1,var2,var3)對應的apply寫法爲:func.apply(func1,[var1,var2,var3])。app

相同點:第一個參數this都同樣,指當前對象。this

不一樣點,第二參數不同,call是一個個的參數列表,apply是一個數組(arguments也能夠)spa

<script type="text/javascript">  
    function  Person(name,age,love){  
        this.name=name;  
        this.age=age;  
        this.love=love;  
        this.say=function say(){  
            alert("姓名:"+name);  
        }  
    }  

    //call方式  
    function student(name,age){  
        Person.call(this,name,age);  
    }  

    //apply方式  
    function teacher(name,love){  
        Person.apply(this,[name,love]);  
        //Person.apply(this,arguments); //跟上句同樣的效果,arguments  
    }  

    //call與aplly的異同:  
    //1,第一個參數this都同樣,指當前對象  
    //2,第二個參數不同:call的是一個個的參數列表;apply的是一個數組(arguments也能夠)  

    var per=new Person("武鳳樓",25,"魏熒屏"); //輸出:「武鳳樓」  
    per.say();  
    var stu=new student("曹玉",18);//輸出:「曹玉」  
    stu.say();  
    var tea=new teacher("秦傑",16);//輸出:「秦傑」  
    tea.say();  

</script>  

 

 

3、對象實例間的繼承 .net

 

 

 

 

原文來自:http://www.jb51.net/article/20431.htmprototype

相關文章
相關標籤/搜索