javascript學習筆記09(建構函式,原型,)

來源:互聯網
上載者:User

標籤:

原型:

<script type="text/javascript">
    /**
     * 以下示範了通過原型的建立方式,使用基於原型的建立可以將屬性和方法
     * 設定為Person專有的,不能再通過window來調用
     */
    function Person(){
        
    }
    Person.prototype.name = "Leon";
    Person.prototype.age = 23;
    Person.prototype.say = function() {
        alert(this.name+","+this.age);
    }
    var p1 = new Person();
    p1.say();
    //通過window沒有辦法調用say方法,如此就完成了封裝
    // say();
    </script>

 

原型的四種狀態:

<script type="text/javascript">
    /**
     * 原型是js中非常特殊一個對象,當一個函數建立之後,會隨之就產生一個原型對象
     * 當通過這個函數的建構函式建立了一個具體的對象之後,在這個具體的對象中
     * 就會有一個屬性指向原型
     */
    //第一種狀態
    function Person(){
        
    }
    //第二種狀態
    Person.prototype.name = "Leon";
    Person.prototype.age = 23;
    Person.prototype.say = function() {
        alert(this.name+","+this.age);
    }
    //第三中狀態,建立了一個對象之後會有一個_prop_的屬性指向原型
    //在使用時如果在對象內部沒有找到屬性會去原型中找,_prop_屬性是隱藏的
    var p1 = new Person();
    //p1.say();
    //以下方法可以檢測出p1是否有_prop_指向Person的原型
    //alert(Person.prototype.isPrototypeOf(p1));
    
    //第四種狀態
    var p2 = new Person();
    //是在自己的空間中定義了一個屬性,不會替換原型中的屬性
    p2.name = "Ada";
    //p2.say();
    //p1.say();
    
    // //檢測某個對象是否是某個函數的原型
    // alert(Person.prototype.isPrototypeOf(p2));
    
    // //檢測某個對象的constructor
    // alert(p1.constructor==Person);
    
    // //檢測某個屬性是否是自己的屬性
    // alert(p1.hasOwnProperty("name"));//false,p1自己的空間中沒有值
    // alert(p2.hasOwnProperty("name"));//true,p2在自己的空間中設定了name屬性
    
    //delete p2.name;
    //p2.say();
    //alert(p2.hasOwnProperty("name"));//由於已經刪除了,所以是false
    
    //檢測某個對象在原型或者自己中是否包含有某個屬性,通過in檢測
    //alert("name" in p1);//true
    //alert("name" in p2);//true
    //alert("address" in p1);//在原型和自己的空間中都沒有,false
    
    alert(hasPrototypeProperty(p1,"name"));//true
    alert(hasPrototypeProperty(p2,"name"));//false
    /**
     * 可以通過如下方法檢測某個屬性是否在原型中存在
     */
    function hasPrototypeProperty(obj,prop) {
        return ((!obj.hasOwnProperty(prop))&&(prop in obj))
    }
    </script>

javascript學習筆記09(建構函式,原型,)

聯繫我們

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