javascript學習筆記11(原型鏈)

來源:互聯網
上載者:User

標籤:

    <script type="text/javascript">
    /**
     * js實現繼承的第一種方式是基於原型鏈的方式
     */
    function Parent() {
        this.pv = "parent";
    }
    Parent.prototype.pp = "ok";
    Parent.prototype.showParentValue = function() {
        alert(this.pv);
    }
    
    function Child() {
        this.cv = "child";
    }
    /**
     * 如果想進行賦值之後,才進行原型鏈的設定,這樣賦值的原型對象
     * 就會被重寫掉,賦值的對象就不存在在新的原型對象中
     */
    // Child.prototype.showChildValue = function() {
        // alert(this.cv);
    // }
    /**
     * 讓Child的原型鏈指向Parent對象,也就等於完成了一次繼承
     * 注意記憶體模型
     */
    Child.prototype = new Parent();
    
    Child.prototype.showChildValue = function() {
         alert(this.cv);
    }
    /**
     * 此時完成的對父類對象的覆蓋
     */
    Child.prototype.showParentValue = function() {
        alert("override parent");
    }
    /**
     * 在使用原型鏈進行繼承一定要注意一下問題:
     * 1、不能在設定了原型鏈之後,再重新為原型鏈賦值
     * 2、一定要在原型鏈賦值之後才能添加或者覆蓋方法
     */
    

    /**
     * 當執行了下面這句話之後,意味著Child的原型又重寫了
     * 這樣就不存在任何的繼承關係了
     * 使用原型鏈需要注意的第一個問題
     */
    // Child.prototype = {
        // showChildValue:function() {
            // alert(this.v);
        // }
    // }
    
    var c = new Child();
    c.showParentValue();
    c.showChildValue();
    alert(c.pp);
    
    </script>

javascript學習筆記11(原型鏈)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.