ES5繼承

原型繼承javascript

<script type="text/javascript">java

    function Father(){}//構造函數數組

    //原型屬性app

    Father.prototype.name = "李四";函數

    Father.prototype.age = 24;this

    //原型方法prototype

    Father.prototype.showName = function(){對象

        return this.name;繼承

    }ip

    Father.prototype.showAge = function(){

        return this.age;

    }

    function Son(){}

    //原型鏈繼承

    //Son.prototype = Father.prototype;

    //Son.prototype = new Father();

    //遍歷父類的原型

    for(var i in Father.prototype){

        Son.prototype[i] = Father.prototype[i];

    }

    var son1 = new Son();

    alert(son1.showName());

    alert(son1.showAge());

</script>

 

經典繼承

<script>

    //構造函數

    function Father(name,age,money){

        //實例屬性

        this.name = name;

        this.age = age;

        this.money = money;

        //實例方法

        this.showName = function(){

            return this.name;

        }

        this.showAge = function(){

            return this.age;

        }

        this.showMoney = function(){

            return this.money;

        }

    }

    function Son(name,age,money,sex){

        //經典繼承、假裝繼承、冒充繼承(call,apply)只能繼承實例

        //Father.apply(this,arguments);

        //Father.call(this,name,age,money);

        Father.apply(this,[name,age,money]);

        this.sex = sex;

        this.showSex = function(){

            return this.sex;

        }

    }

    var son1 = new Son("張三",23,20000,"男");

    alert(son1.showName());

    alert(son1.showAge());

    alert(son1.showMoney());

    alert(son1.showSex());

</script>

call與aplly的異同:

第一個參數this都同樣,指當前對象

第二個參數不同:call的是一個個的參數列表;apply的是一個數組(arguments也能夠)

相關文章
相關標籤/搜索