javascript學習筆記10(基於組合與動態原型建立對象)

來源:互聯網
上載者:User

標籤:

基於組合與動態原型建立對象 

方法一:在外部設定prototype

<script type="text/javascript">
/**
 * 為瞭解決原型所帶來的問題,此處需要通過組合建構函式和原型來實現對象的建立
 * 將屬性在建構函式中定義,將方法在原型中定義
 * 這種有效集合了兩者的優點,是目前最為常用的一種方式
 */
    function Person(name,age,friends){
        //屬性在建構函式中定義
        this.name = name;
        this.age = age;
        this.friends = friends;
    }
    Person.prototype = {
        constructor:Person,
        //方法在原型中定義
        say:function() {
            alert(this.name+"["+this.friends+"]");
        }
    }
    //此時所以的屬性都是儲存在自己的空間中的
    var p1 = new Person("Leon",23,["Ada","Chris"]);
    p1.name = "John";
    p1.friends.push("Mike");//為p1增加了一個朋友
    p1.say();
    var p2 = new Person("Ada",33,["Leon"]);
    //此時原型中就多了一個Mike,這就是原型所帶來的第二個問題
    p2.say();//leon ada chris mike
</script>

 

方法二:內部設定,prototype設定為單例,減少資源浪費

<script type="text/javascript">
/**
 * 為了讓定義的方式更加符合java的需求,就把定義方法的原型代碼放置到Person這個建構函式中
 */
    function Person(name,age,friends){
        //屬性在建構函式中定義
        this.name = name;
        this.age = age;
        this.friends = friends;
        
        //不能使用重寫的方式定義
        /*Person.prototype = {
            constructor:Person,
            //方法在原型中定義
            say:function() {
                alert(this.name+"["+this.friends+"]");
            }
        }*/
        /**
         * 判斷Person.prototype.say是否存在,如果不存在就表示需要建立
         * 當存在之後就不會在建立了
         */
        if(!Person.prototype.say) {
            Person.prototype.say = function() {
                alert(this.name+"["+this.friends+"]");
            }    
        }
    }
    
    //此時所以的屬性都是儲存在自己的空間中的
    var p1 = new Person("Leon",23,["Ada","Chris"]);
    p1.name = "John";
    p1.friends.push("Mike");//為p1增加了一個朋友
    p1.say();
    var p2 = new Person("Ada",33,["Leon"]);
    //此時原型中就多了一個Mike,這就是原型所帶來的第二個問題
    p2.say();//leon ada chris mike
    </script>

javascript學習筆記10(基於組合與動態原型建立對象)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.