方法只不過是附加在對象上的函數。html
在構造器函數內部定義對象的方法:函數
1 <!DOCTYPE html> 2 <html> 3 <body> 4 <script> 5 function person(firstname,lastname,age,eyecolor) 6 { 7 this.firstname=firstname; 8 this.lastname=lastname; 9 this.age=age; 10 this.eyecolor=eyecolor; 11 12 this.changeName=changeName; 13 function changeName(name) 14 { 15 this.lastname=name; 16 } 17 } 18 myMother=new person("Steve","Jobs",56,"green"); 19 myMother.changeName("Ballmer"); 20 document.write(myMother.lastname); 21 </script> 22 23 </body> 24 </html>
運行結果:Ballmerthis