3_多态.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. var __extends = (this && this.__extends) || (function () {
  2. var extendStatics = function (d, b) {
  3. extendStatics = Object.setPrototypeOf ||
  4. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  5. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  6. return extendStatics(d, b);
  7. };
  8. return function (d, b) {
  9. if (typeof b !== "function" && b !== null)
  10. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  11. extendStatics(d, b);
  12. function __() { this.constructor = d; }
  13. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  14. };
  15. })();
  16. // 多态: 父类型的引用指向了子类型的对象 ,不同类型的对象针对相同的方法,产生了不同的行为
  17. (function () {
  18. //定义一个父类
  19. var Animal = /** @class */ (function () {
  20. //定义一个构造函数
  21. function Animal(name) {
  22. this.name = name;
  23. }
  24. //方法
  25. Animal.prototype.run = function (distance) {
  26. if (distance === void 0) { distance = 0; }
  27. console.log("run " + distance + " far away", this.name);
  28. };
  29. return Animal;
  30. }());
  31. //定义一个子类
  32. var Dog = /** @class */ (function (_super) {
  33. __extends(Dog, _super);
  34. //构造函数
  35. function Dog(name) {
  36. //调用父类的构造函数 实现子类中属性的初始化操作
  37. return _super.call(this, name) || this;
  38. }
  39. //实例的方法
  40. Dog.prototype.run = function (distance) {
  41. if (distance === void 0) { distance = 10; }
  42. console.log("run " + distance + " far away", this.name);
  43. };
  44. return Dog;
  45. }(Animal));
  46. var Pig = /** @class */ (function (_super) {
  47. __extends(Pig, _super);
  48. //构造函数
  49. function Pig(name) {
  50. return _super.call(this, name) || this;
  51. }
  52. Pig.prototype.run = function (distance) {
  53. if (distance === void 0) { distance = 20; }
  54. console.log("run " + distance + " far away", this.name);
  55. };
  56. return Pig;
  57. }(Animal));
  58. //实例化父类的对象
  59. var ani = new Animal('动物');
  60. ani.run();
  61. //实例化子类对象
  62. var dog = new Dog('大黄');
  63. dog.run();
  64. var pig = new Pig('佩奇');
  65. pig.run();
  66. /* 父类和子类的关系 可以通过父类的类型 创建子类的类型 */
  67. var dog1 = new Dog('小黄');
  68. var pig1 = new Pig('乔治');
  69. dog1.run();
  70. pig1.run();
  71. /* 函数 */
  72. function showRun(ani) {
  73. ani.run();
  74. }
  75. showRun(dog1);
  76. showRun(pig1);
  77. })();