使用构造器创建 JavaScript 对象

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <h1>JavaScript 对象构造器</h1>
  6.  
  7. <p id="demo"></p>
  8.  
  9. <script>
  10. // Person 对象的构造器函数
  11. function Person(first, last, age, eye) {
  12. this.firstName = first;
  13. this.lastName = last;
  14. this.age = age;
  15. this.eyeColor = eye;
  16. }
  17.  
  18. // 创建 Person 对象
  19. var myFriend = new Person("Bill", "Gates", 62, "blue");
  20.  
  21. // 显示年龄
  22. document.getElementById("demo").innerHTML =
  23. "My friend is " + myFriend.age + ".";
  24. </script>
  25.  
  26. </body>
  27. </html>