javascript面向對象理解的補充

<html>
    <head>
        <title>js inherit demo</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0" max-age="0">
    </head>
    <body>
        <h4>js inherit demo</h4>
    </body>
    <script type="text/javascript">

        //js有兩種對象,一種是函數對象,一種是普通對象
        //函數對象有__proto__和prototype兩種屬性,而普通對象只有__proto__屬性
        //js引擎基於__proto__的遞歸查找是全部js繼承的核心!!!,所以也稱爲基於原型鏈的繼承方式

        /*
        *   當建立一個function時,作了幾件事情
        *   一、建立了一個普通對象base
        *-  二、建立了一個對應的原型變量@base
        *   三、普通對象中的prototype指針指向原型變量
        *   四、原型變量@base中的constructor指針(構造函數)指向base
        */
        var base = function(){
            base.prototype.name = 'hello';
            this.password       = 'fredric';

            console.log('do base constructor');
        }

        console.log(base.prototype.constructor == base); //true

        console.log(base.prototype);
        console.log(base.__proto__);

        //此時b是一個object而非base
        //普通對象只有__proto__屬性指向其原型鏈
        var b = new base(); //do constructor

        /*
        * 一、建立一個空的obj
        * 二、將__proto__綁定到對象的原型,即base.prototype
        * 三、執行base函數
        */
        b.age = 4;
        console.log(b.__proto__ == base.prototype); //true
        console.log(b.__proto__.name == b.name); //true
        console.log(b.password);
        //此時b自己沒有name屬性,因而js引擎會到b的__proto__裏去找,如此往復,所以實現了繼承的效果
        //以下:b.__proto__.__proto__.name
        console.log(b);


        //第二種繼承的方式
        var extend = function(){
            console.log('do extend constructor');
        }
        console.log(extend.prototype.constructor == extend); //true
        

        //執行順序以下:
        //1. 建立一個空的obj賦值給extent.prototype
        //2. extend.prototype.__proto__指向base.prototype
        //3. 執行base函數,即打印do base constructor
        extend.prototype = new base();
        console.log(extend.prototype.__proto__ == base.prototype); //true

        var e = new extend();

        console.log(e.__proto__ == extend.prototype); //true
        console.log(e);

    </script>

</html>
相關文章
相關標籤/搜索