// es5造类/* function Person(name,age) {this.name = name;this.age = age;}Person.prototype.sayName = function() {return this.name;}let p1 = new Person('小马哥',28);console.log(p1);*/class Person {// 实例化的时候会立即被调用constructor(name, age) {this.name = name;this.age = age;}sayName() {return this.name}}// 通过Object.assign()方法一次性向类中添加多个方法Object.assign(Person.prototype, {sayName2() {return this.name},sayAge() {return this.age}})let p1 = new Person('小马哥', 28);console.log(p1);
类的继承
// 使用关键字 extendsclass Animal{// es5造类/* function Person(name,age) {this.name = name;this.age = age;}Person.prototype.sayName = function() {return this.name;}let p1 = new Person('小马哥',28);console.log(p1);*/class Person {// 实例化的时候会立即被调用constructor(name, age) {this.name = name;this.age = age;}sayName() {return this.name}}// 通过Object.assign()方法一次性向类中添加多个方法Object.assign(Person.prototype, {sayName2() {return this.name},sayAge() {return this.age}})let p1 = new Person('小马哥', 28);console.log(p1);constructor(name,age) {this.name = name;this.age = age;}sayName(){return this.name;}sayAge(){return this.age;}}class Dog extends Animal{constructor(name,age,color) {super(name,age);// Animal.call(this,name,age);this.color = color;}// 子类自己的方法sayColor(){return `${this.name}是${this.age}岁了,它的颜色是${this.color}`}// 重写父类的方法sayName(){return this.name + super.sayAge() + this.color;}}let d1 = new Dog('小黄',28,'red');console.log(d1.sayColor());console.log(d1.sayName());
