js對象執行個體化的常見三種方式

來源:互聯網
上載者:User

標籤:pre   構造   rac   工廠   content   txt   window   建立對象   post   

三種常見模式:原廠模式,建構函式模式,原型模式

<span style="font-size:18px;"><!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>Object</title></head><body><h1>建立對象常見的三種方式</h1></body><script>    window.onload=function(){        //原廠模式        function oj(){            var lio=new Object();            lio.name=‘lio‘;            lio.attr=‘男‘;            lio.hobby=function(){                var li=document.createElement("p");                var txt=document.createTextNode("三妹");                li.appendChild(txt);                document.body.appendChild(li);            };            return lio;        }        var person=oj();        //alert(person.name);        //建構函式模式        function oj2(name,age){            this.name=name;            this.age=age;            this.hobby=function(){                var li=document.createElement("p");                var txt=document.createTextNode("三妹");                li.appendChild(txt);                document.body.appendChild(li);            }        }        var person2=new oj2(‘三妹‘,123);        person2.hobby();        alert(person2.name);        //原型模式        function oj3(){            //this.name=‘lio‘;        }        oj3.prototype.name=‘lio‘;        oj3.prototype.love= function (name) {            alert("愛"+name);        };        var person3=new oj3();        //檢測是在執行個體中還是在原型中        alert(person3.hasOwnProperty("name"));        alert(person3.hasOwnProperty("rename"));        person3.love(‘三妹‘);        //混合模式        function oj4(age) {            this.age=age;            this.rename=‘aaaa‘;        };        oj4.prototype={            constructor:oj4,            name:‘lio‘,            age:123,            love: function (name) {                alert(name+"愛三妹");            }        };        var person4=new oj4(18);        alert(person4.hasOwnProperty("age"));//true        person4.love(‘lio‘);    }</script></html></span>


js對象執行個體化的常見三種方式

聯繫我們

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