10.对象创建模式_构造函数+原型的组合模式.html 886 B

12345678910111213141516171819202122232425262728293031323334
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <!--
  11. 方式五:构造函数+原型的组合模式
  12. *套路:自定义构造函数,属性在函数中初始化,方法添加到原型上
  13. *适用场景:需要创建多个类型确定的对象
  14. -->
  15. <script>
  16. function Person(name, age) {//在构造函数中只初始化一般属性
  17. this.name = name
  18. this.age = age
  19. }
  20. Person.prototype.setName = function(name){
  21. this.name = name
  22. }
  23. var p1 = new Person('孙悟空',23)
  24. var p2 = new Person('猪八戒',33)
  25. console.log(p1,p2)
  26. </script>
  27. </body>
  28. </html>