10_类.html 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. <script>
  11. function Person(name,age){
  12. this.name = name
  13. this.age = age
  14. }
  15. /* 所有的构造函数 都有一个prototype 属性 这个属性指向它的原型对象
  16. 原型对象的特点: 声明在原型对象下面的属性和方法 都被所有的实例化对象所共享
  17. 属性写在 构造函数里
  18. 方法写在 原型对象下
  19. */
  20. Person.prototype.eat = function(){
  21. console.log('eat')
  22. }
  23. var p1 = new Person()
  24. p1.eat()
  25. console.log(Person.prototype.constructor)
  26. /*
  27. 继承父类的方法 在子类的构造函数里面 通过调用父类的.call 去继承
  28. 子类的继承对象 = new 父类 继承方法
  29. */
  30. function Coder(name,age){
  31. Person.call(this,name,age)
  32. }
  33. /* 继承父类的方法 */
  34. Coder.prototype = new Person()
  35. Coder.prototype.constructor = Coder
  36. console.log(Coder.prototype.constructor)
  37. var c1 = new Coder('lisi',20)
  38. console.log(c1)
  39. c1.eat()
  40. </script>
  41. </body>
  42. </html>