javascipt對象—成員函數

來源:互聯網
上載者:User

給一個對象添加(指定)函數的幾種方式:

<!DOCTYPE htmlPUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><title></title><link rel="stylesheet" type="text/css" href="float_.css"><script type="text/javascript">    //用構造方法來建立對象    //對象---成員函數    //給一個對象添加(指定)函數的幾種方式/*    //第一種方式:通常方式    function Person(){                this.name="abc";        this.age=18;        this.show=function(){                        window.alert("name:"+this.name+"age:"+this.age);        }    }    var p1=new Person;    p1.show();*/    //第二種方式:/*        function Person(){                this.name="abc";        this.age=19;    }    function show(){                window.alert("name:"+this.name+"age:"+this.age);    }    window.alert(show);//輸出show()函數整體代碼        var p2=new Person();    p2.show1=show; //不要加括弧 【看不懂請看看 window.alert(show) 這個的輸出】    p2.show1();*//*    //第三種方式    function Person(){                this.name="lily";        this.age=19;    }        var p3=new Person();    p3.show=function show2(){                window.alert("name:"+this.name+" "+"age:"+this.age);    }    p3.show();*/    //第四種方式        //前幾種方法有一個問題,那就是以上對象獨佔函數代碼,這樣如果對象過多,則會影響效率,js設計者,給我們提供了別一個方法,原型法:這樣多個對象可以共用函數代碼    function Car(){            }    //使用prototype去綁定一個函數給shot    Car.prototype.show=function(){                window.alert("寶馬");    }    var d1 =new Car();    d1.show();    var d2=new Car();    d2.show();//正確        window.alert(d1.show==d2.show);//返回true 說明shot()方法共用一份,而不是每個對象獨佔一份    window.alert(d1==d2);//對象地址不一樣</script></head><body></body></html>

 

 

聯繫我們

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