今天文章會延續昨天的程式碼去做建構式的學習紀錄
我們先看看原本的程式碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| var player=new Object; player.name="John"; player.hp=100; player.fight=function(){ this.hp=this.hp-2 }; player.rest=function(){ this.hp++ } }; player.report=function(){ alert(this.name+":"+this.hp) }; player.fight(); player.rest(); player.report();
|
這上方指的是John這個角色的部分,如果用上方的程式碼要再建立新的角色,就需要重複上面程式碼,只是換個角色或是名稱,但是一但角色多了之後,整個程式碼就會變成有點混亂,這時候我們可以使用建構式去作出一個模板,接下來要創立新角色就只要套用模板就可以了,方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| function player (name,hp){ this.name=name; this.hp=hp; this.fight=function(){ this.hp-=2 }; this.rest=function(){ this.hp++ }; this.report=function(){ alert(this.name+":"+this.hp) }; }
|
我們可以看到上方做出了基本的模板出來,function player就是我們設定要用來建構物件的函式,內容就是我們規劃出來的樣板,使用this建立新建的空白物件,接著我們要來使用這個樣板,使用方式如下:
1 2 3 4 5 6 7
| var player = new player("John", 100); player.fight(); player.report(); var player2= new player("Bob", 80); player2.rest(); player2.report();
|
參考來源:
https://wcc723.github.io/javascript/2017/12/18/javascript-constructor/
https://www.youtube.com/watch?v=xSu7TbPPy34