1. // es5造类
    2. /* function Person(name,age) {
    3. this.name = name;
    4. this.age = age;
    5. }
    6. Person.prototype.sayName = function() {
    7. return this.name;
    8. }
    9. let p1 = new Person('小马哥',28);
    10. console.log(p1);
    11. */
    12. class Person {
    13. // 实例化的时候会立即被调用
    14. constructor(name, age) {
    15. this.name = name;
    16. this.age = age;
    17. }
    18. sayName() {
    19. return this.name
    20. }
    21. }
    22. // 通过Object.assign()方法一次性向类中添加多个方法
    23. Object.assign(Person.prototype, {
    24. sayName2() {
    25. return this.name
    26. },
    27. sayAge() {
    28. return this.age
    29. }
    30. })
    31. let p1 = new Person('小马哥', 28);
    32. console.log(p1);

    类的继承

    1. // 使用关键字 extends
    2. class Animal{// es5造类
    3. /* function Person(name,age) {
    4. this.name = name;
    5. this.age = age;
    6. }
    7. Person.prototype.sayName = function() {
    8. return this.name;
    9. }
    10. let p1 = new Person('小马哥',28);
    11. console.log(p1);
    12. */
    13. class Person {
    14. // 实例化的时候会立即被调用
    15. constructor(name, age) {
    16. this.name = name;
    17. this.age = age;
    18. }
    19. sayName() {
    20. return this.name
    21. }
    22. }
    23. // 通过Object.assign()方法一次性向类中添加多个方法
    24. Object.assign(Person.prototype, {
    25. sayName2() {
    26. return this.name
    27. },
    28. sayAge() {
    29. return this.age
    30. }
    31. })
    32. let p1 = new Person('小马哥', 28);
    33. console.log(p1);
    34. constructor(name,age) {
    35. this.name = name;
    36. this.age = age;
    37. }
    38. sayName(){
    39. return this.name;
    40. }
    41. sayAge(){
    42. return this.age;
    43. }
    44. }
    45. class Dog extends Animal{
    46. constructor(name,age,color) {
    47. super(name,age);
    48. // Animal.call(this,name,age);
    49. this.color = color;
    50. }
    51. // 子类自己的方法
    52. sayColor(){
    53. return `${this.name}是${this.age}岁了,它的颜色是${this.color}`
    54. }
    55. // 重写父类的方法
    56. sayName(){
    57. return this.name + super.sayAge() + this.color;
    58. }
    59. }
    60. let d1 = new Dog('小黄',28,'red');
    61. console.log(d1.sayColor());
    62. console.log(d1.sayName());