標籤: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