js學習筆記32----new

來源:互聯網
上載者:User

標籤:style   建立   round   對象   scale   win   blank   www   存在   

new:用於建立一個對象。

 

有 new 與 無 new 時的區別,查看下面的範例程式碼應該會增加感覺:

<!DOCTYPE html><html lang="en">    <head>        <title>有 new 的時候</title>        <meta charset="UTF-8">        <meta name="viewport" content="width=device-width, initial-scale=1">        <script>           function show(){               alert(this);           }           show(); //彈出 window           new show(); //彈出 object ,會新建立一個對象        </script>    </head>    <body>    </body></html>

上一篇我們所講的工廠方式存在的2個缺陷可以能過new來解決,最佳化後的代碼如下:

<!DOCTYPE html><html lang="en">    <head>        <title>new</title>        <meta charset="UTF-8">        <meta name="viewport" content="width=device-width, initial-scale=1">        <script>              function createPerson(name,sex){   //建構函式:建立一個對象                //假想的系統內部工作流程                //var this = new Object();                this.name = name;                this.sex = sex;                this.showName = function(){                    alert(‘我的名字叫‘+this.name);                }                this.showSex = function(){                    alert(‘我是‘+this.sex+‘的‘);                }                //假想的系統內部工作流程                //return this;            }            var p1 = new createPerson(‘sese‘,‘女‘);             var p2 = new createPerson(‘JJ‘,‘男‘);            p1.showName();            p1.showSex();            p2.showName();            p2.showSex();                 </script>    </head>    <body>    </body></html>

 

js學習筆記32----new

相關文章

聯繫我們

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