10.原型.html 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. * 所有构造函数下都有两个属性:constructor 和 prototype
  12. * 原型的特点:
  13. * 1.方法 写在原型下
  14. * 2.属性 写在构造函数下
  15. *
  16. */
  17. function Person(name,age) {
  18. this.name = name;
  19. this.age = age;
  20. Person.prototype.eat = function() {
  21. console.log("青草蛋糕")
  22. }
  23. }
  24. let p1 = new Person('LiLi',20);
  25. console.log(p1);
  26. p1.eat();
  27. /**
  28. * 1.令当前子函数的原型 是 当前实例化的父函数
  29. * 2.父对象.call 修改this指向
  30. */
  31. function Child(name,age,a) {
  32. Person.call(this,name,age);
  33. this.a =a;
  34. }
  35. Child.prototype = new Person();
  36. let aa = new Child('HAHA',10,'篮球');
  37. console.log(aa)
  38. aa.eat();
  39. </script>
  40. </body>
  41. </html>