09.对象创建模式_自定义构造函数模式.html 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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>自定义构造函数模式</title>
  8. </head>
  9. <body>
  10. <!--
  11. 方式四:自定义构造函数模式
  12. *套路:自定义构造函数,通过new创建对象
  13. *适用场景:需要创建多个类型确定的对象
  14. *问题:每个对象都有相同的数据,浪费内存
  15. -->
  16. <script>
  17. //定义类型
  18. function Person(name, age) {
  19. this.name = name
  20. this.age = age
  21. this.setName = function (name) {
  22. this.name = name
  23. }
  24. }
  25. var p1 = new Person('孙悟空', 22)
  26. p1.setName('二师兄')
  27. console.log(p1.name, p1.age)
  28. console.log(p1 instanceof Person)
  29. function Student(name, price) {
  30. this.name = name
  31. this.price = price
  32. }
  33. var s = new Student('张三', 900)
  34. console.log(s instanceof Student)
  35. var p2 = new Person('唐僧', 99)
  36. console.log(p1, p2)
  37. </script>
  38. </body>
  39. </html>