19_构造函数.html 946 B

1234567891011121314151617181920212223242526272829303132333435
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <script>
  10. // 构造函数
  11. // 构造函数的首字母一般大写
  12. // this 指向构造函数
  13. function Person(name,age){
  14. this.username = name;
  15. this.age = age;
  16. // this.talk = function(){
  17. // console.log(`我叫${this.username},我今年${this.age}岁`)
  18. // }
  19. }
  20. // 原型上写方法
  21. Person.prototype.talk = function(){
  22. console.log(`我叫${this.username},我今年${this.age}岁`)
  23. }
  24. // 实例化对象
  25. let p1 = new Person("张三",18);
  26. let p2 = new Person("李四",20);
  27. console.log(p1);
  28. console.log(p2);
  29. p1.talk();
  30. p2.talk();
  31. </script>
  32. </body>
  33. </html>