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